c++ Oracle OCCI 编程
OCCI数据库Oracle编程步骤
1. 配置环境
(1) Occi访问数据库需要occi.h头文件,此文件在oracle安装目录下,必须有oracle库的支持。安装oracle服务端或客户端;
(2) 配置NLS_LANG环境变量,必须与数据库的字符编码一致,否则可能出现中文乱码;
(3) 配置环境变量,使客户端支持中文显示;
(4) 安装C++编程工具和g++编译工具。
2. 编写C++程序
(1) Environment类创建occi环境变量;
(2) Environment类下的createConnection方法创建连接数据库的Connection对象;
(3) Statement类创建对象,由数据库连接对象调用createStatement方法创建;
(4) Statement类创建对象调用setSQL()准备SQL语句;
(5) Statement类创建对象调用execute()或executeUpdate()或executeQurey()或executeArrayUpdate()方法执行查询,如果是查询的,创建ResultSet对象接收数据集;如果是数据更新回插入:Statement::
setAutoCommit (TRUE); 设置自动提交;Statement::setAutoCommit(FALSE);
设置手动提交,手动提交:Connection::commit();Connection::rollback();
(6) Statement类创建对象调用getxxx()方法获取字段数据;
(7) terminateStatement()终止Statement对象;
(8) terminateConnection()断开数据库连接;
(9) Environment::terminateEnvironment()终止环境变量。
- #include <iostream>
- #include <occi.h>//occi头文件
- //声明命名空间
- using namespace oracle::occi;
- using namespace std;
- int main ()
- {
- Environment *env;
- Connection *conn;
- Statement *stmt;
- ResultSet *rs;
- string username = "system";//用户名
- string password = "st1234";//密码
- string connstring = "orcl";//数据库连接字符串
- string sql,strname;
- int isno;
- env = Environment::createEnvironment();//创建环境变量
- conn = env->createConnection(username,password,connstring); //创建数据库连接对象
- stmt = conn->createStatement();//创Statement对象
- sql = " SELECT u_id,u_name,to_char(u_date,'yyyy-mm-dd hh24:mi:ss') FROM student";
- stmt->setSQL(sql);//准备SQL语句
- try
- {
- rs = stmt->executeQuery();//执行SQL语句,返回结果集
- while (rs->next()) //取数据
- {
- isno = rs->getInt(1);
- strname=rs->getString(2);
- cout<< isno << " AND " << strname << endl;
- cout<<rs->getString(3)<<endl;
- }
- cout <<"SELECT SUCCESS" << endl;
- }
- catch(SQLException ex) //异常处理
- {
- cout << " Error Number "<< ex.getErrorCode() << endl;
- cout << ex.getMessage() << endl;
- }
- conn->terminateStatement(stmt);//终止Statement对象
- env->terminateConnection(conn);//断开数据库连接
- Environment::terminateEnvironment(env);// 终止环境变量
- return 1;
- }
3. 编写makefile文件
Makefile:
includepath=${ORACLE_HOME}/rdbms/public
libpath=${ORACLE_HOME}/lib
libfile=-L ${libpath} -locci -lclntsh /usr/lib/libstdc++.so.5
incfile=-I ${includepath}
occiselect:select.cpp
g++ -o occiselect select.cpp ${libfile} ${incfile}
clean:
rm occiselect
4. 编译程序
Make occiselect.