在c ++控制台应用程序中编写SQL查询?

时间:2014-11-17 12:49:54

标签: c++ mysql sql c sql-server

我一直在尝试通过我的c ++代码编写sql查询,但我无法做到这一点。我已成功连接服务器,但不知道将查询写入特定数据库的确切方法。我的源代码如下:

#include <windows.h>
#include <stdio.h>  // for printf
#include <sqlext.h>// main SQLAPI++ header
#include <iostream>
#include <conio.h>
#include <string.h>
#include <sqltypes.h>
#include<ATLComTime.h>

using namespace std;
void main(int argc, char* argv[])
{
    SQLHANDLE henv;
    SQLRETURN rc;
    SQLHANDLE hconn;
    SQLSMALLINT bufsize=0;
    SQLINTEGER nativeerror=0;
    SQLSMALLINT textlen=0;
    unsigned char connStrOut[256];
    SQLWCHAR sqlstate[32];
    SQLWCHAR message[256];

    rc = SQLAllocEnv(&henv);
    if (rc != SQL_SUCCESS)
    {
        printf("\nSQLAllocEnv call failed.");
        return;
    }

    rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hconn);
    if (rc != SQL_SUCCESS)
    {
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        printf("\nSQLAllocHandle call failed.");
        return;
    }

    rc = SQLDriverConnect(hconn, NULL, (SQLWCHAR*)TEXT("DRIVER=SQL Server;SERVER=M1-010;DATABASE=GlobalVideoProcessing;UID=AXACT\\muhammad.ahsan;PWD=Axact123;Trusted_Connection=yes;"), SQL_NTS, NULL, 256, &bufsize, SQL_DRIVER_NOPROMPT);
    if (bufsize!=0)
    {
        printf("Connected successfully.\n");
        SQLDisconnect(hconn);
    }
    else
    {
        rc = SQLGetDiagRec(SQL_HANDLE_DBC, hconn, 1, sqlstate, &nativeerror, message, 256, &textlen);

        printf("SQLDriverConnect failed.\n");
        if (rc!=SQL_ERROR)
            printf("%s=%s\n", (CHAR *)sqlstate, (CHAR *)message);
    }

    SQLFreeHandle(SQL_HANDLE_DBC, hconn);
    SQLFreeHandle(SQL_HANDLE_ENV, henv);
    getch();
}

我需要一些指导。希望提出建议

1 个答案:

答案 0 :(得分:0)

我从来没有在c / c ++中编写SQL查询,但这可能会对你有所帮助:http://cs.dvc.edu/HowTo_SQL.html