本文介绍了如何将SQL Server连接到C +程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,
有人知道吗
是否可以将SQL Server与C ++程序连接.
如果是
我需要通过前端C ++程序执行一个简单的查询
谢谢,

Dear All,
Can anybody know
Is it possible to connect SQL Server with C++ Program.
If yes
I need to execute one simple Query through the front end C++ program
Thank you,

推荐答案

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>

using namespace std;

void show_error(unsigned int handletype, const SQLHANDLE& handle)
{
	SQLCHAR sqlstate[1024];
	SQLCHAR message[1024];
	if(SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL))
	cout<<"Message: "<<message<<"\nSQLSTATE: "<<sqlstate<<endl;
}

int main()
{
	SQLHANDLE sqlenvhandle;
	SQLHANDLE sqlconnectionhandle;
	SQLHANDLE sqlstatementhandle;
	SQLRETURN retcode;

	do
	{
		if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle))
			break;

		if(SQL_SUCCESS!=SQLSetEnvAttr(sqlenvhandle,SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
			break;

		if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle))
			break;

		SQLCHAR retconstring[1024];
		switch(SQLDriverConnect (sqlconnectionhandle, NULL,
				(SQLCHAR*)"DRIVER={SQL Server};SERVER=localhost, 1433;DATABASE=MyDatabase;UID=sa;PWD=Admin-123;",
				SQL_NTS, retconstring, 1024, NULL,SQL_DRIVER_NOPROMPT))
		{
			case SQL_SUCCESS_WITH_INFO:
				show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
				break;
			case SQL_INVALID_HANDLE:
			case SQL_ERROR:
				show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
				retcode = -1;
				break;
			default:
				break;
		}

		if(retcode == -1)
			break;

		if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
			break;

		if(SQL_SUCCESS!=SQLExecDirect(sqlstatementhandle, (SQLCHAR*)"select * from testtable", SQL_NTS))
		{
			show_error(SQL_HANDLE_STMT, sqlstatementhandle);
			break;
		}
		else
		{
			char name[64];
			char address[64];
			int id;
			while(SQLFetch(sqlstatementhandle)==SQL_SUCCESS)
			{
				SQLGetData(sqlstatementhandle, 1, SQL_C_ULONG, &id, 0, NULL);
				SQLGetData(sqlstatementhandle, 2, SQL_C_CHAR, name, 64, NULL);
				SQLGetData(sqlstatementhandle, 3, SQL_C_CHAR, address, 64, NULL);
				cout<<id<<" "<<name<<" "<<address<<endl;
			}
		}
	}
	while(FALSE);
	SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle );
	SQLDisconnect(sqlconnectionhandle);
	SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
	SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);

}



#include <windows.h>
#include <stdio.h>

#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")

int main(int argc, char* argv[])
{

HRESULT hr = S_OK;
    try
    {
         CoInitialize(NULL);
          // Define string variables.
        _bstr_t strCnn("Provider=SQLOLEDB.1;Persist Security Info=False;User       ID=username;Password=passwd;Initial Catalog=database;Data Source=(local);Integrated Security=SSPI;");

       _RecordsetPtr pRstAuthors = NULL;

      // Call Create instance to instantiate the Record set
      hr = pRstAuthors.CreateInstance(__uuidof(Recordset));

      if(FAILED(hr))
      {
            printf("Failed creating record set instance\n");
            return 0;
       }

      //Open the Record set for getting records from Author table
      pRstAuthors->Open("SELECT Author_ID,username FROM Author",strCnn, adOpenStatic,     adLockReadOnly,adCmdText);

      //Declare a variable of type _bstr_t
     _bstr_t valField1;
     int valField2;

     pRstAuthors->MoveFirst();

    //Loop through the Record set
    if (!pRstAuthors->EndOfFile)
    {
       while(!pRstAuthors->EndOfFile)
       {
          valField1 = pRstAuthors->Fields->GetItem("username")->Value;
          valField2 = pRstAuthors->Fields->GetItem("Author_ID")->Value.intVal;
          printf("%d - %s\n",valField2,(LPCSTR)valField1);
          pRstAuthors->MoveNext();
       }
    }

   }
   catch(_com_error & ce)
   {
      printf("Error:%s\n",ce.Description);
   }

  CoUninitialize();
  return 0;
}



http://www.codersource.net/C/CDatabase/CADOSelectSample.aspx [ ^ ]



http://www.codersource.net/C/CDatabase/CADOSelectSample.aspx[^]


这篇关于如何将SQL Server连接到C +程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:55