使用C++库 soci 连接oracle 使用案例,编译链接,给出cmakeLists.txt和main.cpp
时间: 2024-02-18 11:02:14 浏览: 186
下面是使用C++库soci连接Oracle数据库的示例程序,包括CMakeLists.txt和main.cpp文件。
CMakeLists.txt文件:
```cmake
cmake_minimum_required(VERSION 3.10)
project(soci_oracle_example)
set(CMAKE_CXX_STANDARD 11)
find_package(Boost REQUIRED COMPONENTS system thread)
find_package(OCI REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
include_directories(${OCI_INCLUDE_DIRS})
add_executable(soci_oracle_example main.cpp)
target_link_libraries(soci_oracle_example
${Boost_LIBRARIES}
${OCI_LIBRARIES}
)
```
main.cpp文件:
```cpp
#include <iostream>
#include <soci/soci.h>
#include <soci/odbc/soci-odbc.h>
#include <soci/oracle/soci-oracle.h>
using namespace soci;
using namespace std;
int main()
{
try
{
session sql(oracle, "service=ORCL user=username password=password");
int id;
string name;
statement stmt = (sql.prepare << "SELECT id, name FROM my_table WHERE id = :id", use(id), into(name));
id = 1;
stmt.execute();
if (stmt.fetch())
{
cout << "id: " << id << ", name: " << name << endl;
}
else
{
cout << "Record not found" << endl;
}
}
catch (exception& e)
{
cerr << "Error: " << e.what() << endl;
}
return 0;
}
```
其中,"username"和"password"是Oracle数据库的用户名和密码,"ORCL"是Oracle数据库的服务名,"my_table"是要查询的表名。
编译链接命令如下:
```
mkdir build
cd build
cmake ..
make
```
如果编译成功,将生成可执行文件soci_oracle_example。
阅读全文