Connecting to SQL Server from C++

Despite being quite a basic requirement, it was very difficult to find anything solid on connecting to a SQL database without using CLR or 3rd party libraries in visual C++. This code was tested and works when connecting to a SQL Server Express 2005 server in Visual Studio 2010 with a win32 console project using visual C++. Thanks to Tidy Tutorials, who look to have scalped it from MSDN (although I couldn’t find it anywhere).

#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=localhost, 1433;DATABASE=MyDatabase;UID=sa;PWD=Admin-123;", 
                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;
    }
    
    if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
        goto FINISHED;

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

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

12 thoughts on “Connecting to SQL Server from C++

      • what are the steps to do this? New to C++ , need to change the db source from Access to SQL server. Also will it work fro 2012? Many Thanks

  1. Very difficult is an understatement I would say. I have spent weeks trying to get an example I could use. The MSDN site is helpful but maybe too generic. At any rate after reading past the point of delirium on the MSDN site I happily found this. Within five minutes I had my task working. Many thanks to you for posting.

  2. Hello, James! Great post. Thanks a lot.

    Your code works when connecting to a SQL Server 2000 server in Visual Studio 2005 with a win32 console project using visual C++ !!!

    I really needed this code.

  3. hi, I don’t know where I will put this code. please, show me the steps until the database appear to me in the data source. thanks for advance

  4. Hi Mr
    Please I need to connect SQL Server 2008 R2 TO visual studio 2010 using c++ , can you help me ?
    Thanks in advance

  5. Hello everyone, I am using visual studio 2013 and sql server 2008, but this code does not go home I do not know where does the erreur.voici the error message: 0040E080nSQLSTATE: 0040E888, Can you help me thank you

  6. show message
    Message: [Microsoft][ODBC SQL Server Driver][DBNETLIB]General network error.Check your network documentation.
    SQLSTATE: 08S01

    please solution this problem
    Note that I used appserv program

  7. James, Thanks very much for this. Its been a while since you posted this. I would be grateful if you could please help with the code that shows how to retrieve all records (all rows) returned by the query and save them in an array that could be then used for other operations. It is so difficult to get information for doing something that is so basic. Thanks for your help

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>