linux occi 数据库连接

来源:互联网 发布:mysql field函数 编辑:程序博客网 时间:2024/04/28 20:20

搭建oracle环境(oracle server / client),配置环境变量

// OCCIConnect.cpp  #include <iostream>#include <occi.h>#include <stdio.h>using namespace std;using namespace oracle::occi;int main(){  Environment *env=Environment::createEnvironment(Environment::DEFAULT);  cout<<"success"<<endl;  string name = "用户名";  string pass = "密码";  string srvName = "服务器地址:1521/实例名";  string date;  try  {    Connection *conn = env->createConnection(name, pass, srvName);    cout<<"conn success"<<endl;//      数据操作,创建Statement对象          Statement *pStmt = NULL;    // Statement对象          pStmt = conn->createStatement();        if(pStmt)                cout<<"success createConnection!"<<endl;        else                cout<<"failure createConnection!"<<endl;        Statement *stmt = conn->createStatement();        string sSQL = "select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual";        stmt->setSQL(sSQL);ResultSet *rs = stmt->executeQuery();        if(rs->next())        {                date = rs->getString(1);        }        cout<<"now time :"<<date<<endl;          // 终止Statement对象          conn->terminateStatement(pStmt);        env->terminateConnection(conn);  }  catch(SQLException e)  {    cout<<e.what()<<endl;  }  Environment::terminateEnvironment(env);  cout<<"end!"<<endl;  return 0;}

shell脚本(本例oracle环境使用的是 server,环境变量需要修改成当前机器的)

basepath=$(cddirname $0; pwd)
export PATH
`export LIBRARY_PATH=添加oracle lib (:oracle安装目录/lib)
export LD_LIBRARY_PATH=添加oracle lib(:oracle安装目录/lib)
export CPLUS_INCLUDE_PATH= 添加oracle头文件(:/opt/oracle/product/11.2.0/rdbms/public)
export NLS_LANG=AMERICAN_AMERiCA.AL32UTF8
export PATH=添加oracle安装目录(:oracle安装目录)
cd $basepath

rm ./occiTest
g++ -o occiTest -ICPLUS_INCLUDE_PATH -LLIBRARY_PATH OCCIConnect.cpp -locci -lclntsh -Wall -O -g(注意修改此行代码,引用环境变量CPLUS_INCLUDE_PATH、LIBRARY_PATH,前面要加引用符号,当前编辑器加入之后乱码)
$basepath/occiTest

运行此shell脚本,生成可执行文件occiTest,运行可以测试oracle是否连接成功
./occiTest
success
ORA-01017: invalid username/password; logon denied
end!

注意gcc版本号:
一开始我在ubuntu16.4中测试,一直连不通,但在centos7中可以连通。发现是gcc版本的问题,ubuntu16.4默认安装的gcc>4.8,centos7中gcc4.8.5,后来到ubuntu14.4(默认安装4.8.5)中试了一下,可以连通。