Linux下C++通过SOCI连接到GBase 8s数据库
操作系统:CentOS 7.8 64-bit
软件需求:
SOCI 4.0.1
GBase 8s CSDK
1,安装CSDK
手工安装CSDK,或者下载免安装版本的CSDK
下载地址:
https://gbasedbt.com/odbc/GBase8s_3.0-Linux64-ODBC-Driver.tar.gz
[root@localhost ~]# wget https://gbasedbt.com/odbc/GBase8s_3.0-Linux64-ODBC-Driver.tar.gz
# 解压至指定目录,如/opt,生成/opt/gbase8s-odbc-driver目录。
[root@localhost ~]# tar -C /opt -zxf GBase8s_3.0-Linux64-ODBC-Driver.tar.gz
设置环境变量文件(也可以写入到/etc/profile中)
# 增加GBASEDBTDIR,LD_LIBRARY_PATH
export GBASEDBTDIR=/opt/gbase8s-odbc-driver
export LD_LIBRARY_PATH=$GBASEDBTDIR/lib:$GBASEDBTDIR/lib/esql:$GBASEDBTDIR/lib/cli:$GBASEDBTDIR/lib/c++:$LD_LIBRARY_PATH
2,安装SOCI
SOCI需要预先安装cmake 2.8+(建议cmake3), gcc-c++
下载地址:
https://github.com/SOCI/soci.git
或者https://sourceforge.net/projects/soci/files/soci/ (建议)
[root@localhost ~]# wget https://netactuate.dl.sourceforge.net/project/soci/soci/soci-4.0.1/soci-4.0.1.tar.gz
[root@localhost ~]# tar -zxvf soci-4.0.1.tar.gz && cd soci-4.0.1
设置环境变量文件(也可以写入到/etc/profile中)
# 增加LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH
编译安装SOCI,建议使用cmake3
[root@localhost soci-4.0.1]# cmake3 -DWITH_BOOST=ON -DSOCI_TESTS=ON
[root@localhost soci-4.0.1]# make
[root@localhost soci-4.0.1]# make install
3,编写测试程序脚本TestSOCIOdbc.cpp
// filename: TestSOCIOdbc.cpp
#include <soci/soci.h>
#include <soci/odbc/soci-odbc.h>
#include<iostream>
#include<istream>
#include<ostream>
#include<string>
#include<exception>
using namespace std;
using namespace soci;
int main() {
cout<<"SOCI 测试程序开始运行.\n\n";
try {
session sql(odbc,"Driver=/opt/gbase8s-odbc-driver/lib/cli/iclit09b.so;HOST=a02.gbasedbt.com;SERV=9088;PROT=onsoctcp;SRVR=gbase01;DB=testdb;U
ID=gbasedbt;PWD=GBase123;DLOC=zh_CN.utf8;CLOC=zh_CN.utf8");
// 删除和创建表
sql<< "drop table if exists company";
sql<< "create table company(coid serial,coname varchar(255),coaddr varchar(255))";
// 插入记录
string cn = "南大通用";
string ca = "天津市海泰绿色产业基地";
sql<< "insert into company(coname,coaddr) values (:cn, :ca)", use(cn), use(ca);
cn = "南大通用北京分公司";
ca = "北京市朝阳区太阳宫";
sql<< "insert into company(coname,coaddr) values (:cn, :ca)", use(cn), use(ca);
// 查询记录
rowset<row> rs = (sql.prepare << "select * from company");
for (rowset<row>::iterator it = rs.begin(); it != rs.end(); ++it)
{
const row& row = *it;
cout << "coid:" << row.get<int>(0)
<< " coname:" << row.get<string>(1)
<< " coaddr:" << row.get<string>(2) << endl;
}
} catch (exception const &e) {
cerr<<"Error:" <<e.what()<<endl;
}
cout<<"\nSOCI 测试程序结束运行.\n";
}
4,编译C++程序,测试连接GBase 8s数据库测试
[root@localhost ~]# g++ -Wall -g -o TestSOCIOdbc TestSOCIOdbc.cpp -lsoci_core -lsoci_odbc
[root@localhost ~]# ./TestSOCIOdbc
SOCI 测试程序开始运行.
coid:1 coname:南大通用 coaddr:天津市海泰绿色产业基地
coid:2 coname:南大通用北京分公司 coaddr:北京市朝阳区太阳宫
SOCI 测试程序结束运行.