我正在尝试使用SQLDriverConnect连接到Microsoft SQL数据库:
int DatabaseHelper::ConnectDatabase()
{
SQLSMALLINT i, MsgLen;
SQLWCHAR SqlState[6];
SQLRETURN rc2;
SQLINTEGER NativeError[1];
SQLWCHAR Msg[SQL_MAX_MESSAGE_LENGTH];
retCode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle);
if (retCode != SQL_SUCCESS)
return retCode;
retCode = SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
if (retCode != SQL_SUCCESS)
return retCode;
retCode = SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnectionHandle);
if (retCode != SQL_SUCCESS)
return retCode;
retCode = SQLDriverConnect(sqlConnectionHandle, NULL, (SQLWCHAR*)L"Driver={SQL Server Native Client 11.0};Server = 192.168.56.56\SQLEXPRESS;Database = PCTOOLS; Uid = sa; Pwd = delphi2006; ", SQL_NTS, retConString, 1024, NULL, SQL_DRIVER_NOPROMPT);
i = 1;
rc2 = SQLGetDiagRec(SQL_HANDLE_STMT, sqlConnectionHandle, i, SqlState, NativeError,
Msg, sizeof(Msg), &MsgLen);
return retCode;
}
运行时,retCode获取值-1,而rc2将获得值-2。 SqlState,NativeError或Msg中没有返回任何值(它们保留在未初始化的值)。 我正在使用Visual C ++ 2015。
答案 0 :(得分:1)
感谢Phil指出正确的方向。
由于服务器名称中的单个反斜杠以及连接字符串属性之间的空格,SQLDriverConnect失败。
由于句柄类型不正确导致SQLGetDiagRec失败 - 应该是SQL_HANDLE_DBC
更正SQLDriverConnect调用:
retCode = SQLDriverConnect(sqlConnectionHandle, NULL, (SQLWCHAR*)L"Driver={SQL Server Native Client 11.0};Server=192.168.56.56\\SQLEXPRESS;Database=PCTOOLS;Uid=sa;Pwd=delphi2006;", SQL_NTS, retConString, 1024, &dwLength, SQL_DRIVER_NOPROMPT);
更正SQLGetDiagRec调用:
rc2 = SQLGetDiagRec(SQL_HANDLE_DBC, sqlConnectionHandle, i, SqlState, NativeError,
Msg, sizeof(Msg), &MsgLen);
答案 1 :(得分:0)
Server =
行上的SQLDriverConnect
属性看起来很可疑。
尝试使用Server = 192.168.56.56\\SQLEXPRESS
(注意双反斜杠)以逃避您尝试传递给函数的单个反斜杠。