要在C++中連接到Oracle數(shù)據(jù)庫(kù),您需要使用Oracle Call Interface (OCI) 或 Oracle C++ Call Interface (OCCI)。以下是使用OCCI的示例代碼:
首先,確保已安裝Oracle客戶端和OCCI庫(kù)。您可以從Oracle官方網(wǎng)站下載這些庫(kù)。
包含必要的頭文件:
#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()) {
// 處理查詢結(jié)果
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
注意:請(qǐng)將/path/to/oracle/client/lib
替換為實(shí)際的Oracle客戶端庫(kù)路徑。
這只是一個(gè)簡(jiǎn)單的示例,您可以根據(jù)需要修改代碼以滿足您的需求。有關(guān)更多信息和示例,請(qǐng)參閱Oracle OCCI文檔:https://docs.oracle.com/en/database/oracle/oracle-database/19/lncpp/index.html