⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ibmdb2connection.cpp

📁 C++连接一写常用数据库的接口
💻 CPP
📖 第 1 页 / 共 2 页
字号:
// -----------------------------------------------------------------------------// DB2Connection::DB2Connection// -----------------------------------------------------------------------------DB2Connection::DB2Connection(      int argc,       const char** argv):     BaseConnection(DB2_DRIVERNAME),   _henv(SQL_NULL_HENV),   _numHandles(0),   _handles(NULL){   // Store any arguments in a easy to use structure. (Must be even number)   // All argument names will be in lowercase.      // -- No argument processing at present            // Create the DB2 environment handle   SQLRETURN cliRC = SQL_SUCCESS;   cliRC = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &_henv);      if (cliRC != SQL_SUCCESS)   {      printf("Unable to initialize DB2 environment. Is DB2INSTANCE=xxx exported correctly\n");      throw Error("Unable to allocate DB2 Environment handle");   }       // Set attribute to enable application to run as ODBC 3.0 application    cliRC = SQLSetEnvAttr(_henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);} // DB2Connection::DB2Connection// -----------------------------------------------------------------------------// DB2Connection::~DB2Connection// -----------------------------------------------------------------------------DB2Connection::~DB2Connection(){	// Make sure we disconnect from the database.	if (isConnected)	{		disconnect(120);  // 2 Minute timeout.	}   // Free any handles.      _freeCollection(CONNECTION_HANDLES);      // Free the DB2 environment handle   SQLFreeHandle(SQL_HANDLE_ENV, _henv);} // DB2Connection::~DB2Connection// -----------------------------------------------------------------------------// DB2Connection::connect// -----------------------------------------------------------------------------void DB2Connection::connect(      const string &username,       const string &password,       const string &databaseName,       const string &host,       int          maxConnections,      int          minConnections,      const string &optParam1,      const string &optParam2){   // Synchronize the function.   SimpleThread_Synchronize sync(classMutex);   // Make sure we are not already connected.   if (isConnected)      throw ErrorConnecting("connect(): Already connected to the database.");   // Check and set the parameters. (Use the base class for this)   BaseConnection::connect(username, password, databaseName, host,      maxConnections, minConnections, optParam1, optParam2);   // Free any handles used before.   _freeCollection(CONNECTION_HANDLES);         // Create the collection to hold the needed handle information.   _numHandles = maxConnections;   _handles = (DB2Handle**)malloc(_numHandles * sizeof(DB2Handle*));   for (int i=0; i<_numHandles; i++)   {      _handles[i] = new DB2Handle();      _handles[i]->status = BaseHandle::DISCONNECTED;   }         // Connect the required specified minimum connections. The rest will be on demand.   for (int j=0; j<minConnections; j++)      _db2Connect(j);   isConnected = true;      } // DB2Connection::connect// -----------------------------------------------------------------------------// DB2Connection::disconnect// -----------------------------------------------------------------------------voidDB2Connection::disconnect(      time_t timeout){   // Synchronize the function.   SimpleThread_Synchronize sync(classMutex);   bool doneTimeout = false;   // Only disconnect if we are connected.   if (!isConnected)      throw NotConnected("disconnect(): Not connected to the database.");        // Disconnect all the open connections.   for (int i=0; i<_numHandles; i++)   {      // Free the query object if it is still attached.      // TODO      if (_handles[i]->status == BaseHandle::CONNECTED ||           _handles[i]->status == BaseHandle::CONNECTED_USED)      {         // If the handle is USED wait for the timeout.         // Only wait once for the timeout for all connections.         if (_handles[i]->status == BaseHandle::CONNECTED_USED && !doneTimeout)         {            SimpleThread::sleep(timeout * 1000);            doneTimeout = true;         }                     _db2Disconnect(i);      }   }              isConnected = false;   } // DB2Connection::disconnect// -----------------------------------------------------------------------------// DB2Connection::requestQueryConnection// -----------------------------------------------------------------------------void*DB2Connection::requestQueryConnection(){   // This function must act as a fifo stack. The first thread in must get the first    //   available connection.   // Synchronize the function.   SimpleThread_Synchronize sync(classMutex);      // Make sure we are connected.   if (!isConnected)      throw NotConnected("requestQueryConnection(): Not connected to the database.");    // Flag that a request is occuring.   isRequestQueryConnectionOccuring = true;      // Loop until we have a valid connection or an error.   // Built in timeout of 1 min per thread to retrieve a connection.   int i;   time_t now = time(NULL);   while (time(NULL) <= now + 60)   {      // Try and obtain a connection      for (i=0; i<_numHandles; i++)      {         // We have an available handle thats already connected.         if (_handles[i]->status == BaseHandle::CONNECTED)         {            _handles[i]->queryObject = new DB2Query(this, i);            _handles[i]->status = BaseHandle::CONNECTED_USED;            isRequestQueryConnectionOccuring = false;            return _handles[i]->queryObject;         }                  // We have an available handle that needs to be connected.         if (_handles[i]->status == BaseHandle::DISCONNECTED)         {            _db2Connect(i);            _handles[i]->queryObject = new DB2Query(this, i);            _handles[i]->status = BaseHandle::CONNECTED_USED;            isRequestQueryConnectionOccuring = false;            return _handles[i]->queryObject;         }      }      // Sleep for a second to conserve resources      SimpleThread::sleep(1000);   }   // If we got this far a timeout occured.   isRequestQueryConnectionOccuring = false;   throw QueryConnectionTimeout("requestQueryConnection(): A timout occured "         "while trying to obtain a query connection.");} // DB2Connection::requestQueryConnection// -----------------------------------------------------------------------------// DB2Connection::releaseQueryConnection// -----------------------------------------------------------------------------voidDB2Connection::releaseQueryConnection(   void* queryObject){   // Don't synchronize as we may need to release a connection to allow   //  requestQueryConnection to get an available one      // Find the handle that has the query connection instance   int i;   for (i=0; i<_numHandles; i++)   {      if (_handles[i]->queryObject == queryObject)      {         _handles[i]->queryObject = NULL;         _handles[i]->status = BaseHandle::CONNECTED;                  // Check if we need to release the connection.         // We release the connection if the connection is outside of the minimum         // connections and there is no current request for a connection waiting.         if (i >= minConnections && !isRequestQueryConnectionOccuring)         {            _db2Disconnect(i);         }                 break;      }   }} // DB2Connection::releaseQueryConnection

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -