Efficient way to test ODBC connection

纵饮孤独 提交于 2019-12-22 04:00:48

问题


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:

  • Platform is Windows 2003 / 2008 R2
  • DB is SQL Server 2005 / 2008 R2
  • Connection method is ODBC
  • Programming language is C++

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


回答1:


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.



来源:https://stackoverflow.com/questions/7424298/efficient-way-to-test-odbc-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!