1.下载对应的oracle-instantclient,例如:
instantclient-basic-linux-11.2.0.3.0.zip //包含动态链接库等
instantclient-sdk-linux-11.2.0.3.0.zip //包含开发所需的头文件等
2.通过WinScp上传至redhat5,例如用户为fanbin,目录为/home/fanbin/oracle,分别进行解压
unzip instantclient-basic-linux-11.2.0.3.0.zip
unzip instantclient-sdk-linux-11.2.0.3.0.zip
ln -s instantclient_11_2 instantclient
进入解压的目录
ln -s libclntsh.so.11.1 libclntsh.so
ln -s libocci.so.11.1 libocci.so
3.设置环境变量,例如在/home/fanbin根目录下:
vi .bash_profile
添加以下内容:
ORACLE_HOME=/home/fanbin/oracle/instantclient
export LD_LIBRARY_PATH=$ORACLE_HOME
export NLS_LANG=AMERICAN_AMERICA.ZHS16GBK
export TNS_ADMIN=$ORACLE_HOME
PATH=/sbin:$PATH:$HOME/bin
export PATH
4.在$ORACLE_HOME下创建tnsnames.ora,添加以下内容:
fbdb =
(DESCRIPTION =
(FAILOVER = ON)
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.101)(PORT = 1521))
)
(CONNECT_DATA =
(SID=fbdb)
)
)
注意:需要根据数据库配置进行修改、
5.上传测试代码,
文件名为test.cpp,例如:
#include <iostream>
#include <occi.h>
//#pragma comment(lib,"oraocci11d.lib")
using namespace std;
using namespace oracle::occi;
int main()
{
Environment *env=Environment::createEnvironment();//初始化occi环境
//用户输入密码,名字,数据库
string name = "fanbin";
string pwd = "***";
string dbname = "fbdb";
string dbname = "fbdb";
//用以下字符串就不用配置tnsnames.ora了
//string dbname ="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=192.168.0.101) (PORT=1521)) (CONNECT_DATA=(SERVICE_NAME=fbdb)))";
//string dbname ="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=192.168.0.101) (PORT=1521)) (CONNECT_DATA=(SID=fbdb)))";
try
{
Connection *conn=env->createConnection(name,pwd,dbname);//创建到oracle的连接
cout<<"您已成功连接数据库!"<<endl;
string strQuery("select * from test");
Statement *stmt=conn->createStatement(strQuery);//创建查询语句
ResultSet *rs;//创建记录集用于返回查询的结果
rs=stmt->executeQuery();//执行查询语句
//next用于从记录集中获取下一行数据
while (rs->next())
{
cout<<rs->getInt(1)<<":"<<rs->getString(2)<<":"<<rs->getString(3)<<endl;
}
//删除
stmt->setSQL("delete from test where id =:id");
stmt->setInt(1,4);
if(stmt->executeUpdate()==1)
{
cout<<"删除一条记录"<<endl;
}
else
{
cout<<"记录不存在"<<endl;
}
//插入
stmt->setSQL("insert into test values(:id,:key,:value2)");
stmt->setInt(1,4);
stmt->setString(2,"中");
stmt->setString(3,"国");
if(stmt->executeUpdate()!=1)
{
cout<<"插入失败"<<endl;
}
//修改
stmt->setSQL("update test set key =:key where id=:id");
stmt->setInt(2,4);
stmt->setString(1,"中1");
if(stmt->executeUpdate()!=1)
{
cout<<"修改失败"<<endl;
}
stmt->closeResultSet(rs);//关闭记录集
conn->terminateStatement(stmt);//关闭语句
env->terminateConnection(conn);//关闭连接
}
catch(SQLException e)
{
cout<<"fbin:"<<e.what()<<endl;//捕获错误
}
Environment::terminateEnvironment(env);//关闭环境
return 0;
}
6.编译及运行
编译:
g++ test.cpp -I$ORACLE_HOME/sdk/include -L$LD_LIBRARY_PATH -lociei -lclntsh -lnnz11 -locci -g -o test
运行:
./test