简体   繁体   中英

How can I check in C++ code connection to SQL Server database?

Database: Microsoft SQL Server - any version

Preferably the easiest way (without connecting third-party libraries). You just need to test connectivity

In the task cannot be used .Net Framework and it is not advisable to MFC

The project in Visual Studio 2008 Professional

CDatabase * db = new CDatabase ();
if (!db->OpenEx (args [2], CDatabase::noOdbcDialog))
{
    printf ("Failed to connect to DB\n");
    ExitProcess (1);
}
db->Close();

This code on the MFC is not suitable because it requires the installation of Redistributable. It is desirable to use the WinAPI.

Thank you for your attention.

UPD:

    SQLHANDLE hEnv, hDbc;

SQLAllocHandle (SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv);
SQLSetEnvAttr (hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, NULL);
SQLAllocHandle (SQL_HANDLE_DBC, hEnv, &hDbc);

LPSTR lpConnectionString = args [2];
LPSTR lpOutputString = new CHAR [256];
SQLSMALLINT sLength;
SQLRETURN sqlRet = SQLDriverConnect(hDbc, 0, (SQLCHAR*)lpConnectionString, strlen (lpConnectionString), (SQLCHAR*)lpOutputString, 255, &sLength, SQL_DRIVER_NOPROMPT);

args[2] = "DRIVER={SQL Server};SERVER={VM7\\SQLEXPRESS};Database={master}";

VM7 is name of my machine

There are only 2 'Native' database libraries that ship with Windows. They are ODBC and OLEDB. Given that OLEDB is a COM based interface and requires significantly more knowledge I'm only going to discuss the ODBC solution here.

The code below is bare bones and is there only to provide hints on how to solve the problem.

#include <Windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>

#define MAX_STRING_LEN 255

int main()
{
    SQLHANDLE henv, hdbc;

    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
    SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_ODBC_VER, SQL_IS_INTEGER);
    SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

    wchar_t* connection_string = L"Driver={SQL Server};Server=<address>;Database=<database name>;Uid=<username>;Pwd=<password>";
    wchar_t output_string[MAX_STRING_LEN + 1];
    SQLSMALLINT out_length;
    SQLDriverConnect(hdbc, 0, connection_string, lstrlen(connection_string), output_string, MAX_STRING_LEN, &out_length, SQL_DRIVER_NOPROMPT);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM