在C++中實現Oracle數據庫連接池,可以使用Oracle官方提供的Oracle Call Interface (OCI) 庫
首先,確保已經安裝了Oracle客戶端庫和OCI庫。可以從Oracle官網下載并安裝。
包含必要的頭文件:
#include <occi.h>
#include<iostream>
#include<vector>
#include <mutex>
#include<condition_variable>
class OracleConnectionPool {
public:
OracleConnectionPool(const std::string& connectionString, const std::string& userName, const std::string& password, int poolSize);
~OracleConnectionPool();
oracle::occi::Connection* getConnection();
void releaseConnection(oracle::occi::Connection* connection);
private:
std::vector<oracle::occi::Connection*> connections_;
std::vector<bool> connectionStatus_;
std::mutex mutex_;
std::condition_variable cv_;
};
OracleConnectionPool::OracleConnectionPool(const std::string& connectionString, const std::string& userName, const std::string& password, int poolSize) {
for (int i = 0; i< poolSize; ++i) {
oracle::occi::Environment* env = oracle::occi::Environment::createEnvironment(oracle::occi::Environment::DEFAULT);
oracle::occi::Connection* conn = env->createConnection(userName, password, connectionString);
connections_.push_back(conn);
connectionStatus_.push_back(true);
}
}
OracleConnectionPool::~OracleConnectionPool() {
for (auto conn : connections_) {
conn->close();
oracle::occi::Environment::terminateEnvironment(conn->getEnvironment());
}
}
oracle::occi::Connection* OracleConnectionPool::getConnection() {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] { return std::any_of(connectionStatus_.begin(), connectionStatus_.end(), [](bool status) { return status; }); });
auto it = std::find(connectionStatus_.begin(), connectionStatus_.end(), true);
size_t index = std::distance(connectionStatus_.begin(), it);
connectionStatus_[index] = false;
return connections_[index];
}
void OracleConnectionPool::releaseConnection(oracle::occi::Connection* connection) {
std::unique_lock<std::mutex> lock(mutex_);
auto it = std::find(connections_.begin(), connections_.end(), connection);
size_t index = std::distance(connections_.begin(), it);
connectionStatus_[index] = true;
cv_.notify_one();
}
int main() {
OracleConnectionPool pool("localhost:1521/XE", "username", "password", 5);
oracle::occi::Connection* conn = pool.getConnection();
oracle::occi::Statement* stmt = conn->createStatement("SELECT * FROM your_table");
oracle::occi::ResultSet* rs = stmt->executeQuery();
while (rs->next()) {
// 處理查詢結果
}
stmt->closeResultSet(rs);
conn->terminateStatement(stmt);
pool.releaseConnection(conn);
return 0;
}
這樣就實現了一個簡單的Oracle數據庫連接池。請注意,這個實現僅作為示例,實際應用中可能需要根據需求進行調整和優化。