C++ 连接oracle数据库

本文介绍了两种在C++中连接Oracle数据库的方法:使用OCCI和使用OCI。通过代码示例展示了OCCI的简洁性,并指出虽然两者在执行效率上可能相差不大,但OCCI在程序员调用便利性上更胜一筹,更适合未来项目选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式1,使用OCCI:

直接上代码

#include <iostream>
#include <string>
#include <vector>
#include <occi.h>

using namespace oracle::occi;
using std::vector;
using namespace std;

class conndba
{
	private:

		Environment *env;

		Connection *conn;

		Statement *stmt;

	public:

		conndba(string user, string password, string db)

		{

			env = Environment::createEnvironment(Environment::DEFAULT);

			conn = env->createConnection(user, password, db);

		}

		~conndba()

		{

			env->terminateConnection(conn);

			Environment::terminateEnvironment(env);

		}

		void insertBind(string s1, string s2, string s3, string s4)
		{

			string sqlStmt = "INSERT INTO t_user(userid, username, loginname, createdate) VALUES (:1, :2, :3, :4)";  

			stmt=conn->createStatement (sqlStmt);

			try
			{

				stmt->setString(1, s1);

				stmt->setString(2, s2);

				stmt->setString(3, s3);

				stmt->setString(4, s4);

				stmt->executeUpdate();

				cout << "insert - Success" << endl;

			}
			catch (SQLException ex)

			{

				cout << "Exception thrown for insertBind" << endl;
				cout << "Error number: " << ex.getErrorCode() << endl;
				cout << ex.getMessage() << endl;
			}
			conn->terminateStatement(stmt);
		}
		void updateRow(string s1, string s2)
		{
			string sqlStmt = "UPDATE t_user SET userid = :x WHERE username = :y";
			stmt = conn->createStatement(sqlStmt);
			try
			{
				stmt->setString(1, s2);
				stmt->setString(2, s1);
				stmt->executeUpdate();
				cout << "update - Success" << endl;
			}
			catch (SQLException ex)
			{
				cout << "Exception thrown for updateRow" << endl;
				cout << "Error number: " << ex.getErrorCode() << endl;
				cout << ex.getMessage() << endl;
			}
			conn->terminateStatement(stmt);
		}
		void deleteRow(string s1)
		{
			string sqlStmt = "DELETE FROM t_user WHERE userid = :x";
			stmt = conn->createStatement(sqlStmt);
			try
			{
				stmt->setString(1, s1);
				stmt->executeUpdate();
				cout << "delete - Success" << endl;
			}
			catch (SQLException ex)
			{
				cout << "Exception thrown for deleteRow" << endl;
				cout << "Error number: " << ex.getErrorCode() << endl;
				cout << ex.getMessage() << endl;
			}
			conn->terminateStatement(stmt);
		}
		void displayAllRows()
		{
			string sql =
					"select userid, username, loginname, createdate from t_user";
			stmt = conn->createStatement(sql);
			ResultSet *rs = stmt->executeQuery();
			try
			{
				while (rs->next())
				{
					cout << "userid: " << rs->getInt(1) << "\t"
					cout << "username: " << rs->getString(2) <&l
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值