user390935
user390935

Reputation: 255

Efficient way to test ODBC connection

Our product is a TCP listening transaction processor. Incoming connections are assigned a thread to handle the connection and a DB connection to work with.

Rather than costly approach of establishing new DB connection for each incoming client connection, we maintain a pool of database connections.

The database connection pool fairly configurable: min / max sizes, growth rates, etc.

Some details:

Finally, the question:

As the service could be running for several months without a restart, there's a real chance that some of the database connections in the pool become invalid. I want to have as quick a way as possible to test the validity of a given connection before assigning it to an incoming connection.

Currently, I do this by executing the simple SQL statement "SELECT 123;", however I've found that this has significant negative performance impacts when parallel execution plans are used.

Very briefly in code, what I'm doing is:

// ... at some point we decide pool needs another connection...

// Set up database connection
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
SQLAllocHandle(SQL_HANDLE_DBC, env, &conn);
SQLDriverConnect(conn, 0, in_str, in_len, out_str, DIM(out_str), &out_len, SQL_DRIVER_NOPROMPT);

// 'conn' is placed in DB connection pool

// ... some time later a new client connection comes in ...

// Execute simple statement to test if 'conn' is still OK
SQLAllocHandle(SQL_HANDLE_STMT, conn, &stmt);
SQLExecDirect(stmt, (SQLCHAR*)"SELECT 1;", SQL_NTS);

// If 'conn' is OK, give it to incoming connection;
// if not, get another connection from pool

Cheers,
Dave

Upvotes: 9

Views: 7266

Answers (1)

Nick Gorham
Nick Gorham

Reputation: 1143

Well the official way is SQLGetConnectAttr( SQL_ATTR_CONNECTION_DEAD ) which tests if the connection was working when last attempted.

Or SQLGetConnectAttr(conn, SQL_COPT_SS_CONNECTION_DEAD, ...) which tests if the connection is working now.

Upvotes: 11

Related Questions