【解決方法】SQL Server を C+ プログラムに接続する方法

プログラミングQA

[ad_1]

親愛なるみんな、
誰か知ってますか
SQL Server と C++ プログラムを接続することは可能ですか。
そうであれば
フロントエンド C++ プログラムを通じて 1 つの単純なクエリを実行する必要があります
ありがとう、

解決策 2

ODBC を使用して SQL サーバーに接続するには、以下のコードを使用できます。

#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);

}

解決策 3

解決策 4

以下の C++ ADO 選択クエリのサンプルは一目瞭然です。 コードを実行する場合は、コードをコピーして Win32 またはコンソール アプリケーションに貼り付け、接続文字列と SQL ステートメントを編集して、プログラムをコンパイルします。

#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[^]

解決策 5

#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)
{
     SQLWCHAR sqlstate[1024];
     SQLWCHAR message[1024];
     if(SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL))
         cout<<"Message: "<<message<<"\nSQLSTATE: "<<sqlstate<<endl;
 }
int _tmain(int argc, _TCHAR* argv[])
{
	SQLHANDLE sqlenvhandle;    
    SQLHANDLE sqlconnectionhandle;
    SQLHANDLE sqlstatementhandle;
    SQLRETURN retcode;
	if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle))
		goto FINISHED;
	if(SQL_SUCCESS!=SQLSetEnvAttr(sqlenvhandle,SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)) 
		goto FINISHED;
	if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle))
		goto FINISHED;

	SQLWCHAR retconstring[1024];
	switch(SQLDriverConnect (sqlconnectionhandle, 
                 NULL, 
                 (SQLWCHAR*)"DSN=test;UID=sa;PWD=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);
             goto FINISHED;
         default:
             break;
     }
     
     if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
         goto FINISHED;
 
     if(SQL_SUCCESS!=SQLExecDirect(sqlstatementhandle, (SQLWCHAR*)"select * from testtable", SQL_NTS))
	 {
         show_error(SQL_HANDLE_STMT, sqlstatementhandle);
         goto FINISHED;
     }
     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;
         }
     }
 
 FINISHED:
     SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle );
     SQLDisconnect(sqlconnectionhandle);
     SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
     SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);

 
	return 0;
}

解決策 6

Yes, it is indeed possible to connect SQL Server with a C++ program. To do this, you can use the SQL Server Native Client (SNAC) library, which provides a set of APIs for connecting to and interacting with SQL Server databases. Here are the general steps to achieve this:

Include Necessary Headers: In your C++ program, include the necessary header files for SQL Server connectivity. The key header is <sqlncli.h> for the SQL Server Native Client.

Initialize SQL Server: Initialize the SQL Server Native Client library using SQLAllocHandle and SQLSetEnvAttr functions to set up the environment.

Establish a Connection: Use the SQLConnect function to establish a connection to your SQL Server instance. You will need to provide the connection string, which includes server details, authentication credentials, and the database name.

Execute Queries: You can use functions like SQLExecDirect or SQLPrepare followed by SQLExecute to execute SQL queries against the connected database.

Fetch Results: If your query returns results, use functions like SQLFetch to retrieve data rows from the result set.

Error Handling: Implement error handling to check for any issues that may occur during the connection or query execution.

Here's a simplified example of connecting to SQL Server and executing a query in C++:

cpp
Copy code
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>

int main() {
    SQLHENV hEnv;
    SQLHDBC hDbc;
    SQLHSTMT hStmt;
    
    // Initialize the environment
    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv);
    SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER);

    // Initialize the connection
    SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc);
    SQLDriverConnect(hDbc, NULL, (SQLCHAR*)"DSN=your_dsn;UID=your_username;PWD=your_password;", SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE);

    // Initialize the statement
    SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt);

    // Execute a sample query
    SQLExecDirect(hStmt, (SQLCHAR*)"SELECT * FROM your_table", SQL_NTS);

    // Fetch and process results here

    // Cleanup
    SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
    SQLDisconnect(hDbc);
    SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
    SQLFreeHandle(SQL_HANDLE_ENV, hEnv);

    return 0;
}
Make sure to replace placeholders like your_dsn, your_username, your_password, and your_table with your actual SQL Server configuration and query.

As for "codium.ai," it can be a valuable resource for code analysis and quality improvement, including ensuring that your C++ code adheres to best practices when interacting with databases like SQL Server.

[ad_2]

コメント

タイトルとURLをコピーしました