我一直在尝试使用odbc将记录插入sql server数据库,但有一些问题。下面的程序是在visual studio上使用控制台c ++的代码。
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
RETCODE rc;
HENV henv;
HDBC hdbc;
HSTMT hstmt;
SDWORD cdData;
cout << "Attempting Connection " << endl;
SQLAllocEnv(&henv);
SQLAllocConnect(henv, &hdbc);
rc = SQLConnect(hdbc, L"DatasourceTest", SQL_NTS, 0, SQL_NTS, 0, SQL_NTS);
if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO))
{
cout << "Cannot open database -- make sure ODBC is confugured properly." << endl;
SQLFreeConnect(hdbc);
SQLFreeEnv(henv);
cout << "Press ENTER to continue." << endl;
cin.get();
return 1;
}
else
{
cout << "Connected -- ODBC is confugured properly." << endl;
}
//Create a SQL statement
UCHAR szSqlStr[] = "INSERT INTO PERSONS (FirstName, LastName) VALUES ('Jack', 'Benson')";
cout << "Executing " << szSqlStr << endl;
rc = SQLAllocStmt(hdbc, &hstmt);
rc = SQLPrepare(hstmt, (SQLWCHAR*)szSqlStr, sizeof(szSqlStr));
rc = SQLExecute(hstmt);
cout << "rc" << rc << endl;
cout << "SQL_SUCCESS" << SQL_SUCCESS << endl;
cout << "SQL_SUCCESS_WITH_INFO" << SQL_SUCCESS_WITH_INFO << endl;
if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO))
{
//ERROR
SQLWCHAR sqlState[8];
SQLWCHAR msgText[1024];
SQLINTEGER NativeErrorPtr;
SQLSMALLINT TextLengthPtr;
SQLGetDiagRec(SQL_HANDLE_STMT, hstmt, 1, sqlState, &NativeErrorPtr, msgText, sizeof(msgText), &TextLengthPtr);
SQLFreeStmt(hstmt, SQL_DROP);
SQLDisconnect(hdbc);
SQLFreeConnect(hdbc);
SQLFreeEnv(henv);
cout << "Error " << endl << msgText << endl;
cout << "Press ENTER to continue." << endl;
}
cin.get();
return 0;
}
我在这个帖子中附加了程序的输出。返回的RETCODE为-1,屏幕截图中显示此错误。我无法将任何记录插入数据库。与数据库的连接没问题。每次执行程序时错误代码都不同。
答案 0 :(得分:0)
主要错误是您将ANSI字符串传递给SQLPrepare的unicode版本。
UCHAR szSqlStr[] = "INSERT INTO PERSONS (FirstName, LastName) VALUES ('Jack', 'Benson')";
...
rc = SQLPrepare(hstmt, (SQLWCHAR*)szSqlStr, sizeof(szSqlStr));
将程序的字符集更改为ANSI或将请求字符串转换为unicode。另外,您应该考虑最后一个参数取符号长度而不是字节