sql server数据库连接到c ++ visual studio

时间:2015-02-13 03:09:10

标签: c++ visual-studio-2013 localdb sql-server-2014

我在本地服务器上有一个用户数据库,一切似乎都运行正常。唯一的问题是我无法从我的C ++控制台应用程序连接。代码中的连接字符串是正确的,但我认为我使用的参数不正确。任何帮助,将不胜感激。

#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){
SQLCHAR sqlstate[1024];
SQLCHAR 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;

    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle))
    goto FINISHED;

    if (SQL_SUCCESS != SQLSetEnvAttr(sqlenvhandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
    goto FINISHED;

    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle))
    goto FINISHED;

    SQLCHAR retconstring[1024];
    switch (SQLDriverConnect(sqlconnectionhandle,
        NULL,
        (SQLCHAR*)"DRIVER={SQL Server};SERVER=(localdb)\\ProjectsV12;        Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;DATABASE=SampleDatabase1;",
    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);
    goto FINISHED;
default:
    break;

    //Data Source=(localdb)\\ProjectsV12;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False
}

    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
    goto FINISHED;

    if (SQL_SUCCESS != SQLExecDirect(sqlstatementhandle, (SQLCHAR*)"SELECT * FROM User", SQL_NTS)){
    show_error(SQL_HANDLE_STMT, sqlstatementhandle);
    goto FINISHED;
   }
    else{
        char username[64];
        char password[64];
        int id;
    while (SQLFetch(sqlstatementhandle) == SQL_SUCCESS){
        SQLGetData(sqlstatementhandle, 1, SQL_C_ULONG, &id, 0, NULL);
        SQLGetData(sqlstatementhandle, 2, SQL_C_CHAR, username, 64, NULL);
        SQLGetData(sqlstatementhandle, 3, SQL_C_CHAR, password, 64, NULL);
        cout << id << " " << username << " " << password << endl;
    }
}

FINISHED:
    SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle);
    SQLDisconnect(sqlconnectionhandle);
    SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
    SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);

}

0 个答案:

没有答案