SQL connection from Visual C++ Windows Form project

Viewed 2830

I'm very new to C++. just created a C++ Windows Forms project using Visual Studio Community 2015. And used the below main function to obtain a SQL connection.

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

using namespace std;

int main()
{

#define SQL_RESULT_LEN 240
#define SQL_RETURN_CODE_LEN 1000
    //define handles and variables
    SQLHANDLE sqlConnHandle;
    SQLHANDLE sqlStmtHandle;
    SQLHANDLE sqlEnvHandle;
    SQLWCHAR retconstring[SQL_RETURN_CODE_LEN];
    //initializations
    sqlConnHandle = NULL;
    sqlStmtHandle = NULL;
    //allocations
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle))
        goto COMPLETED;
    if (SQL_SUCCESS != SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
        goto COMPLETED;
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle))
        goto COMPLETED;
    //output
    cout << "Attempting connection to SQL Server...";
    cout << "\n";
    //connect to SQL Server  

    switch (SQLDriverConnect(sqlConnHandle,
        NULL,
        (SQLWCHAR*)L"Server=P2005\SQLEXPRESS2014;Database=CPPDB;User Id=myuid;Password=mypswd;",

        SQL_NTS,
        retconstring,
        1024,
        NULL,
        SQL_DRIVER_NOPROMPT)) {
    case SQL_SUCCESS:
        cout << "Successfully connected to SQL Server";
        cout << "\n";
        break;
    case SQL_SUCCESS_WITH_INFO:
        cout << "Successfully connected to SQL Server";
        cout << "\n";
        break;
    case SQL_INVALID_HANDLE:
        cout << "Could not connect to SQL Server";
        cout << "\n";
        goto COMPLETED;
    case SQL_ERROR:
        cout << "Could not connect to SQL Server";
        cout << "\n";
        goto COMPLETED;
    default:
        break;
    }
    //if there is a problem connecting then exit application
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlConnHandle, &sqlStmtHandle))
        goto COMPLETED;
    //output
    cout << "\n";
    cout << "Executing T-SQL query...";
    cout << "\n";
    //if there is a problem executing the query then exit application
    //else display query result
    if (SQL_SUCCESS != SQLExecDirect(sqlStmtHandle, (SQLWCHAR*)L"SELECT @@VERSION", SQL_NTS)) {
        cout << "Error querying SQL Server";
        cout << "\n";
        goto COMPLETED;
    }
    else {
        //declare output variable and pointer
        SQLCHAR sqlVersion[SQL_RESULT_LEN];
        SQLINTEGER ptrSqlVersion;
        while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) {
            SQLGetData(sqlStmtHandle, 1, SQL_CHAR, sqlVersion, SQL_RESULT_LEN, &ptrSqlVersion);
            //display query result
            cout << "\nQuery Result:\n\n";
            cout << sqlVersion << endl;
        }
    }
    //close connection and free resources
COMPLETED:
    SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle);
    SQLDisconnect(sqlConnHandle);
    SQLFreeHandle(SQL_HANDLE_DBC, sqlConnHandle);
    SQLFreeHandle(SQL_HANDLE_ENV, sqlEnvHandle);
    //pause the console window - exit when key is pressed
    cout << "\nPress any key to exit...";
    getchar();
    return 0;
}

When I build and run the above code, It always gives "Could not connect to SQL Server". SQL connection string is given below as,

"Server=P2005\SQLEXPRESS2014;Database=CPPDB;User Id=myuid;Password=mypswd;"

I got the above connection string format from this link. And I'm using Microsoft SQL Server 2014 via SQL Management Studio.

Note : It always triggers the SQL_ERROR case in switch. I'm trying to trace the error. But I didn't get any luck.

Why this occurs?

Any help would be appreciated. Thanks.

2 Answers

This is a suggestion.

Try Visual C++ MFC Template.

Include belows.

//For CDatabase class
#include "odbcinst.h"
#include "afxdb.h"
//

Do below stuff anywhere you want.

    CDatabase database;
    CString SqlString;
    CString strID, strName, strAge;
    CString sDriver = L"ODBC Driver 11 for SQL Server";
    CString sDsn;
    int iRec = 0;

    // Build ODBC connection string
    sDsn.Format(L"ODBC;DRIVER={%s};DSN='';DBQ=%s;DATABASE=MYDBNAME", sDriver, NULL);
    TRY{
        // Open the database
        database.Open(NULL,false,false,sDsn);

    SqlString = "INSERT INTO MY_TABLE (id,name,age) VALUES (1,'Sanjaya',25)";
    database.ExecuteSQL(SqlString);
    // Close the database
    database.Close();
    }CATCH(CDBException, e) {
        // If a database exception occured, show error msg
        AfxMessageBox(L"Database error: " + e->m_strError);
    }
    END_CATCH;

You should create ODBC Datasource, and it should specify as "ODBC Driver 11 for SQL Server". I'm using VS Community 2015 and SQL Server 2014.

just add a backslash in your instance name P2005\SQLEXPRESS2014 P2005\\SQLEXPRESS2014

Related