2016-09-14 171 views
1

我一直在尝试使用odbc插入记录到sql server数据库,但有一些问题。下面的程序是在Visual Studio上使用控制台C++的代码。无法插入数据到SQL Server数据库ODBC 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; 
} 

enter image description here

我已经在这个线程附加程序的输出。返回的RETCODE为-1,在屏幕截图中显示此错误。我无法将任何记录插入到数据库中。与数据库的连接没问题。每次程序执行时,错误代码都是不同的。

+0

我会尝试'SQLExecDirect'来代替。 (因为声明没有参数。) – jarlh

+0

我已经尝试使用SQLExecDirect,但事实证明具有相同的错误。 –

回答

0

主要错误是您将ANSI字符串传递给unicode版本的SQLPrepare。

UCHAR szSqlStr[] = "INSERT INTO PERSONS (FirstName, LastName) VALUES ('Jack', 'Benson')"; 
... 
rc = SQLPrepare(hstmt, (SQLWCHAR*)szSqlStr, sizeof(szSqlStr)); 

将程序的字符集更改为ANSI或将请求字符串转换为unicode。你也应该考虑到最后一个参数在符号长度不是字节