要在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