要在C++中連接到Oracle數據庫,您需要使用Oracle Call Interface (OCI) 或 Oracle C++ Call Interface (OCCI)。以下是使用OCCI的示例代碼:
首先,確保已安裝Oracle客戶端和OCCI庫。您可以從Oracle官方網站下載這些庫。
包含必要的頭文件:
#include <occi.h>
#include<iostream>
oracle::occi::Connection* createConnection(const std::string& username, const std::string& password, const std::string& connectionString) {
oracle::occi::Environment* env = oracle::occi::Environment::createEnvironment();
oracle::occi::Connection* conn = env->createConnection(username, password, connectionString);
return conn;
}
void executeQuery(oracle::occi::Connection* conn, const std::string& query) {
oracle::occi::Statement* stmt = conn->createStatement(query);
oracle::occi::ResultSet* rs = stmt->executeQuery();
while (rs->next()) {
// 處理查詢結果
std::cout << rs->getString(1)<< std::endl;
}
delete rs;
delete stmt;
}
int main() {
try {
std::string username = "your_username";
std::string password = "your_password";
std::string connectionString = "your_connection_string"; // 格式為 "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=your_host)(PORT=your_port))(CONNECT_DATA=(SERVICE_NAME=your_service_name)))"
oracle::occi::Connection* conn = createConnection(username, password, connectionString);
std::string query = "SELECT * FROM your_table";
executeQuery(conn, query);
delete conn;
} catch (oracle::occi::SQLException& ex) {
std::cerr << "Error: " << ex.getMessage()<< std::endl;
}
return 0;
}
g++ -o main main.cpp -L/path/to/oracle/client/lib -locci -lclntsh
注意:請將/path/to/oracle/client/lib
替換為實際的Oracle客戶端庫路徑。
這只是一個簡單的示例,您可以根據需要修改代碼以滿足您的需求。有關更多信息和示例,請參閱Oracle OCCI文檔:https://docs.oracle.com/en/database/oracle/oracle-database/19/lncpp/index.html