Oliver Spryn
Oliver Spryn

Reputation: 17358

C++ ODBC Check if Connection Was Successful

I am using C++ ODBC to connect to a local SQL Server.

Once I have attempted to make connecton to the server; Is there a way to validate that the connection was indeed successful?

Here is a sample of my code, which delegates the connection handles and makes the connection:

//Allocate the pre-connection handles
  this->sReturn = SQL_SUCCESS;
  this->sReturn = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &this->eHandle);
  this->sReturn = SQLSetEnvAttr(this->eHandle, SQL_ATTR_ODBC_VERSION, reinterpret_cast<void*>(SQL_OV_ODBC3_80), 4);
  SQLAllocHandle(SQL_HANDLE_DBC, this->eHandle, &this->cHandle);

//Connect to the database
  this->sReturn = SQLConnect(this->cHandle, reinterpret_cast<SQLWCHAR*>(serverName), SQL_NTS, NULL, 0, NULL, 0);

Upvotes: 2

Views: 2313

Answers (1)

Mark Stevens
Mark Stevens

Reputation: 2366

According to MSDN, the return values of SQLConnect() are:

SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_ERROR, SQL_INVALID_HANDLE, or SQL_STILL_EXECUTING.

So I'm assuming SQL_SUCCESS or SQL_SUCCESS_WITH_INFO indicate the connection was indeed successful.

If by "validate", you mean something other than just looking at the return code, I would imagine any subsequent call using the connection would fail if for some reason the connection were no longer valid.

Here's a code example from the same MSDN site - note they check for success OR success with info:

    // Connect to data source
    retcode = SQLConnect(hdbc, (SQLCHAR*) "NorthWind", SQL_NTS, (SQLCHAR*) NULL, 0, NULL, 0);

    // Allocate statement handle
    if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
        retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); 

       // Process data
       if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
          SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
       }

       SQLDisconnect(hdbc);
    }

Upvotes: 2

Related Questions