c++odbcdriverdsn

How to connect to ODBC DSN through c++


I made a PostgreSQL30 data source name. I tested it and I managed to connect to that dsn through ODBC data source window manager. There was a button Test and It showed message dialog, telling me that connection was success.

Now I wonder how would I connect to that DSN through c++ code and get some data.

This is my code, i saw few examplex online and come up with this code

enter code here

HENV hEnv = NULL; // for allocating memory usingSQLAllocEnv
HDBC hDBC = NULL; // connection handler
HSTMT hStmt = NULL; // statement handler
const char* szDSN = "PostgreSQL30"; // DataSourceName (config in windows 
control panel)
const char* szUID = "postgres"; //username of the database
const char* szPasswd = "postgres"; //password of the database

RETCODE retcode;
int rcod = 1;
int i, j, no = 2;



int main()
{ 
  retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv);

  std::cout << retcode << std::endl;

  SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);

  retcode = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDBC);

  std::cout << retcode << std::endl;

   retcode = SQLConnectA(hDBC,(SQLCHAR*)szDSN, SQL_NTS, (SQLCHAR*)szUID, SQL_NTS, 
  (SQLCHAR*)szPasswd, 
  SQL_NTS);


std::cout << (SQLCHAR*)szUID << std::endl;


if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
    // connected!!
    std::cout << "Hello World!\n SUCCESSS COME ON PLEASE";
}
else {
    std::cout << retcode << std::endl;
}


SQLFreeHandle(SQL_HANDLE_ENV, &hEnv);
SQLFreeHandle(SQL_HANDLE_DBC, &hDBC);

}

But I cant comprehend why would this work, I mean how is this code knows to call SQLAllocHandle implemented by Postgres driver ?

My question is how would I connect to DSN thorugh C++ code and get some data


Solution

  • In fact ODBC Driver Manager makes these calls to ODBC driver when performing your SQLConnect call: on this stage it "knows" which driver you want to use. Look at the SQLConnect function description, "Comments" section:

    "The Driver Manager does not connect to a driver until the application calls a function (SQLConnect, SQLDriverConnect, or SQLBrowseConnect) to connect to the driver. Until that point, the Driver Manager works with its own handles and manages connection information. When the application calls a connection function, the Driver Manager checks whether a driver is currently connected to for the specified ConnectionHandle:

    The driver then allocates handles and initializes itself."

    Full text here: SQLConnect function comments