0

Greeting guys , I have been looking on the internet on how to connect C++ code with SQLEXPRESS DATABASE, I have read some threads about how to connect but yet... I CAN NOT follow any of them... neither they are working for me.

I dont want to use MFC or any kind of C++ methods for DB , I want to do it via raw coding.

problem:

  1. the Database connectable via Visual studio and via Microsoft SQL Server Studio , I can add or drop tables as I LIKE, I believe the DB as it is, is working fine

  2. the C++ code is here " I am Connecting to a local DB "

  3. I got this code from one of the threads and was not able to figure out how to do the SQLDriverConnect,

  4. I am very noob in C++... adding SQLEXPRESS on top of that...

edit:

  1. I dont know what that 3055 in the connect code is...

thank you in advance for help

Data base information:

UDL: this what I got from the udl

( Provider=SQLOLEDB.1;Integrated Security=SSPI;
  Persist Security Info=False;User ID=sa;Initial Catalog=Holpa;Data Source=AMH )

Microsoft server:

Server type: Database Engine
Server name: AMH
Authen: SQL server Authen
Login: sa 
password : amh999

VisualStudio:

Data Source=AMH;Initial Catalog=Holpa;User ID=sa;Password=***********

.NET Framework Data Provider for SQL Server

Open
Microsoft SQL Server
Owner sa

running on local machine.

#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>

using namespace std;

SQLHANDLE sqlenvhandle = SQL_NULL_HANDLE;
SQLHANDLE sqlconnectionhandle = SQL_NULL_HANDLE;
SQLHANDLE sqlstatementhandle = SQL_NULL_HANDLE;
SQLRETURN retcode;
void show_error(RETCODE rc, SQLHENV hEnv, SQLHDBC hDbc,
SQLHSTMT hStmt, const char *action)
{
    SQLWCHAR szMessage[256];
    SQLWCHAR szState[6];
    SDWORD sdwNative;
    SWORD swMsgLen;

    SQLError(hEnv, hDbc, hStmt, szState, &sdwNative, szMessage,
    sizeof(szMessage), &swMsgLen);
    wcout << "wcout MESSAGE: " << szMessage << "\n SQLSTATE " << szState <<      endl;
    printf("Error %d performing %s\n SQLState=%s\nSQL message=%s\n",rc, action, szState, szMessage);
}

void CloseSQL()
{
    SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle);
    SQLDisconnect(sqlconnectionhandle);
    SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
    SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
}


int main()
{

if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle))
{
    printf("huh \n");
    CloseSQL();
    goto END;
}

if (SQL_SUCCESS != SQLSetEnvAttr(sqlenvhandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
{
    printf("huh \n");
    CloseSQL();
    goto END;
}

if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle))
{
    printf("huh \n");
    CloseSQL();
    goto END;
}
printf("Driver Initialised\n");
SQLWCHAR retconstring[1024];
printf("about to Driver Conneect\n");
retcode = SQLDriverConnect(sqlconnectionhandle,
    NULL,
    (SQLWCHAR*)"DRIVER={SQL Server};SERVER=AMH, 3055;DATABASE=Holpa;UID=sa;PWD=amh999;",
    SQL_NTS,
    retconstring,
    1024,
    NULL,
    SQL_DRIVER_NOPROMPT);


if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
 printf("Connection made\n");
}
else
{
 show_error(retcode, sqlenvhandle, sqlconnectionhandle, sqlstatmenthandle, "Connecting.");
}

END:
    printf("\n");
    printf("Program End, press enter key to exit!");
    getchar(); // waits for input 
    return 0;
}

ERRORS: the error codes are not constants... they keep changing ... example I got the following: Message: 0022E1EC SQLSTATE: 0022e9f4

re-run the program Message: 009fdc4c SQLSTATE: 009fe454

rerun the code Message: 00aadd90 SQLSTATE: 00aae598

ahmad
  • 1
  • 5
  • Use ODBC to connect SQL Server. – i486 Mar 19 '16 at 21:50
  • thanks for the answer , I have made connection using ODBC and was able to use Microsoft Access to access that DB. worked like charm. However, I want to make my C++ code to be able to access my DB. – ahmad Mar 20 '16 at 01:42

1 Answers1

0

Firstly, you need a diagonostic function that works:

void show_error(RETCODE rc, SQLHENV hEnv, SQLHDBC hDbc,
                SQLHSTMT hStmt, const char *action)
{
    char szMessage[256];
    char szState[6];
    SDWORD sdwNative;
    SWORD swMsgLen;

    SQLError(hEnv, hDbc, hStmt, szState, &sdwNative, szMessage, 
        sizeof(szMessage),  &swMsgLen);
    printf("Error %d performing %s\n"
        "SQLState=%s\nSQL message=%s\n",
        rc, action, szState, szMessage);
}

Then call it if anything goes wrong, e.g.:

if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
    printf("Connection made\n");
}
else
{
    show_error(retcode, sqlenvhandle, sqlconnectionhandle, sqlstatmenthandle, "Connecting.");
}
  • thanks for the comment, I added the show_error , and the error code i am getting is not constant neither I can lookup for it in google. – ahmad Mar 19 '16 at 19:13
  • the error codes are not constants... they keep changing ... example I got the following: Message: 0022E1EC SQLSTATE: 0022e9f4 re-run the program Message: 009fdc4c SQLSTATE: 009fe454 rerun the code Message: 00aadd90 SQLSTATE: 00aae598 – ahmad Mar 20 '16 at 18:24
  • OK, I don't think your `show_error()` function works properly in that case. I have added mine to my answer. –  Mar 20 '16 at 18:53
  • I have changed the char szMessage and char szState to SQLWCHAR to be compatible with SQLError variables.However , I made another cout<< to show the szMessage and szState , the output is the same as the old show_error the error is not constant . the printf in the code gives Error -1 performing Connecting SqlState =I , SQL message = [ – ahmad Mar 20 '16 at 21:56
  • You can't send an `SQLWCHAR ` to `cout`; it will just print the pointer address, which is different every time. You need to convert it to a `char*` before you can print it. –  Mar 20 '16 at 22:25
  • Or you could send it to `wcout`. –  Mar 20 '16 at 22:32
  • NOW I have proper errors... Omg Martin... ok here the errors , Message: [Microsoft][ODBC Driver Manager][ Data source name not found and no default driver specified SQLSTATE: IM002 ERROR : -1 – ahmad Mar 21 '16 at 01:05
  • I don't think the UDL file is setting up an ODBC data source. Try setting it up in the ODBC Manager in Control Panel. –  Mar 21 '16 at 07:39
  • Control Panel -> Administrative Tools -> ODBC Data Sources 32/64 bits , I added User/System DSN for both and they do connect to the Database. is that what you were referring to? – ahmad Mar 21 '16 at 21:17
  • That error message means the ODBC data source isn't recognised, so either it isn't set up properly or you're not specifying it correctly when attempting to connect. –  Mar 21 '16 at 21:20
  • to be honest I am not sure how to/make sure of the ODBC is setup correctly or not – ahmad Mar 22 '16 at 01:51
  • Try this: http://stackoverflow.com/questions/2702739/simplest-way-to-test-odbc-on-windows –  Mar 22 '16 at 07:07
  • have changed my Driver string to : L"DRIVER={SQL Server};SERVER= (local)SQLEXPRESS;DATABASE=master;UID=sa;PWD=amh999;" and I got different error this time , 08001 and seems there is attempts to connect. Now will follow your link – ahmad Mar 22 '16 at 17:16
  • I got the follow: dbc: szSqlState = "01000", *pfNativeError = 5701, szErrorMsg = "[Microsoft][ODBC SQL Server Driver][SQL Server]Changed database context to 'Holpazz'." dbc: szSqlState = "01000", *pfNativeError = 5703, szErrorMsg = "[Microsoft][ODBC SQL Server Driver][SQL Server]Changed language setting to us_english." Full Connect: Full Connect(Default) Successfully connected to DSN 'AMH'. – ahmad Mar 24 '16 at 05:16
  • i had that output from ODBC Test 32, the sql runner is not working properly – ahmad Mar 24 '16 at 05:17