我正在尝试使用以下代码在C ++中连接SQL Server,但我收到相同的错误“[Microsoft] [ODBC驱动程序管理器]未找到数据源名称且未指定默认驱动程序”
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;
SQLWCHAR retconstring[1024];
switch(SQLDriverConnect (sqlconnectionhandle, NULL,
(SQLWCHAR*)"DRIVER={SQL Server};SERVER=(IPADDRESS\\SQLEXPRESS);DATABASE=test;UID=sa;PWD=abcd$1234;",
SQL_NTS, retconstring, 1024, NULL,SQL_DRIVER_NOPROMPT))
{
case SQL_SUCCESS_WITH_INFO:
//show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
retcode = 0;
break;
case SQL_INVALID_HANDLE:
case SQL_ERROR:
//show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
SQLWCHAR sqlstate[1024];
SQLWCHAR message[1024];
if(SQL_SUCCESS == SQLGetDiagRec(SQL_HANDLE_DBC, sqlconnectionhandle, 1, sqlstate, NULL, message, 1024, NULL))
{
retcode = -1;
break;
}
default:
break;
}
if(retcode == -1)
break;
if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
break;
if(SQL_SUCCESS!=SQLExecDirect(sqlstatementhandle, (SQLWCHAR*)"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);
}
}
}
while(FALSE);
SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle );
SQLDisconnect(sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
目前的配置如下:
但所有这些设置都会出现相同的错误。
如果我遗漏了任何内容,或者我需要更改连接字符串,或者是否有其他方法可以在C ++中连接SQL Server,请告诉我。
答案 0 :(得分:0)
我刚刚在连接字符串参数中添加了_T并且它有效。
(SQLWCHAR*)_T("DRIVER={SQL Server};SERVER=(IPADDRESS\\SQLEXPRESS);
DATABASE=test; UID=sa;PWD=abcd$1234;")