简体   繁体   English

如何检查C ++代码与SQL Server数据库的连接?

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

Database: Microsoft SQL Server - any version 数据库:Microsoft SQL Server-任何版本

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 在任务中不能使用.Net Framework,因此不建议使用MFC

The project in Visual Studio 2008 Professional Visual Studio 2008专业版中的项目

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. MFC上的此代码不合适,因为它需要安装可再发行组件。 It is desirable to use the WinAPI. 希望使用WinAPI。

Thank you for your attention. 感谢您的关注。

UPD: 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}"; args [2] =“ DRIVER = {SQL Server};服务器= {VM7 \\ SQLEXPRESS};数据库= {master}”;

VM7 is name of my machine VM7是我的机器的名称

There are only 2 'Native' database libraries that ship with Windows. Windows仅附带2个“本机”数据库库。 They are ODBC and OLEDB. 它们是ODBC和OLEDB。 Given that OLEDB is a COM based interface and requires significantly more knowledge I'm only going to discuss the ODBC solution here. 鉴于OLEDB是基于COM的接口,并且需要大量知识,所以我仅在这里讨论ODBC解决方案。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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