我一直在尝试连接到Azure 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)
{
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 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;
SQLWCHAR retconstring[1024];
/*switch (SQLDriverConnect(sqlconnectionhandle, NULL,
L"Driver={ODBC Driver 10 for SQL Server};Server=tcp:xyz.database.windows.net;Database=ProjectLIT;UID=auser;PWD=zzzzz;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;",
SQL_NTS, retconstring, 1024, NULL, SQL_DRIVER_NOPROMPT)*/
switch (SQLDriverConnect(sqlconnectionhandle, NULL,
L"DRIVER={SQL Server};SERVER=xyz.database.windows.net,1433;DATABASE=ProjectLIT;UID=auser;PWD=zzzzz;",
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, L"SELECT * FROM Emploees_Res", SQL_NTS))
if (SQL_SUCCESS != SQLExecDirect(sqlstatementhandle, L"SELECT [Internal Email ID] FROM [Emploees_Res] WHERE [Office Acc]=63", SQL_NTS))
{
show_error(SQL_HANDLE_STMT, sqlstatementhandle);
break;
}
else
{
char name[64];
while (SQLFetch(sqlstatementhandle) == SQL_SUCCESS)
{
SQLGetData(sqlstatementhandle, 1, SQL_C_CHAR, name, 64, NULL);
cout << name;
}
}
} while (FALSE);
SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
}
我认为错误可能在连接字符串中。
有人可以告知需要更正的地方吗?提前谢谢。
答案 0 :(得分:0)
非常感谢所有人,
最后得到了解决方案,正如 quentin 所说的那样使用了L宽字符串文字
以下是确切的连接字符串
switch(SQLDriverConnect(sqlconnectionhandle,NULL, L“DRIVER = {SQL Server}; Server = tcp:xyz.database.windows.net,1433; DATABASE = ProjectLIT; UID = auser; PWD = zzzzzz; Encrypt = yes; TrustServerCertificate = no; Connection Timeout = 30;”, SQL_NTS,retconstring,1024,NULL,SQL_DRIVER_NOPROMPT))