参考博客原文链接:https://blog.csdn.net/weixin_41049188/article/details/106606192
一 :下载和配置客户端连接套件:
连接套件在oracle 官方的下载地址:https://www.oracle.com/database/technologies/instant-client/downloads.html 注意区分 x86和 x64。
两个压缩包:sdk(头文件,lib) 和 windows x64 基本客户端(内涵 .dll) 。
下载后可按如图命名并解压到电脑:
二:配置与引用:
打开vs2019,新建一个项目,然后新增属性表OCCI_Oracle(起名随意)
1:配置头文件引用:在 SDK 中:
E:\xuexi\occi\instantclient_sdk\instantclient_19_11\sdk\include。这个不做强制规定,根据个人习惯来放置文件。
打开项目属性:C/C++ / 附加包含目录。
2:引用 lib 文件
E:\xuexi\occi\instantclient_sdk\instantclient_19_11\sdk\lib\msvc\vc14
打开项目属性:连接器 / 常规 / 附加库目录。
3:添加静态库。
连接器 / 输入 / 附加依赖项 添加 oraocci19d.lib 静态库 。需要注意的是,文件中有两个lib,一个是oraocci12.lib,另一个是oraocci12d.lib文件。第一个lib文件是用在release模式的,第二个lib文件是用在debug模式的。
4 引用动态库。
动态库 dll 文件比较大,这里不用拷贝到项目中,使用添加 环境变量 来引用:E:\xuexi\occi\instantclient_basic\instantclient_19_11 在环境变量 path 中添加。
三、测试连接
#include <iostream>
#define WIN32COMMON //避免函数重定义错误
#include <occi.h>
using namespace std;
using namespace oracle::occi;
int main()
{
system("pause");
//创建OCCI上下文环境
Environment* env = Environment::createEnvironment();
if (NULL == env) {
printf("createEnvironment error.\n");
return -1;
}
else
cout << "success" << endl;
string name = "scott";
string pass = "tiger";
string srvName = "localhost:1521/orcl";
try
{
//创建数据库连接
Connection* conn = env->createConnection(name, pass, srvName);//用户名,密码,数据库名
if (NULL == conn) {
printf("createConnection error.\n");
return -1;
}
else
cout << "conn success" << endl;
// 数据操作,创建Statement对象
Statement* pStmt = NULL; // Statement对象
pStmt = conn->createStatement();
if (NULL == pStmt) {
printf("createStatement error.\n");
return -1;
}
//--------查询---------
// 指定DML为自动提交
pStmt->setAutoCommit(TRUE);
// 设置执行的SQL语句
pStmt->setSQL("SELECT * FROM JAVATEST1");
// 执行SQL语句
std::string strTemp;
ResultSet* pRs = pStmt->executeQuery();
while (pRs->next()) {
strTemp = pRs->getString(3);
printf("user:%s.\n", strTemp.c_str());
}
pStmt->closeResultSet(pRs);
// 终止Statement对象
conn->terminateStatement(pStmt);
// 关闭连接
env->terminateConnection(conn);
// pEnv->terminateConnection(pConn);
}
catch (SQLException e)
{
cout << e.what() << endl;
system("pause");
return -1;
}
// 释放OCCI上下文环境
Environment::terminateEnvironment(env);
cout << "end!" << endl;
system("pause");
return 0;
}
四、实际运行引发的错误:
我自己运行时一开始出现了这个错误:由于找不到oraocci19d.dll无法继续执行代码......
然后我的解决方案:将E:\xuexi\occi\instantclient_basic\instantclient_19_11目录下的oraocci19d.dll,oraocci19.dll,oraociei19.dll,oraons.dll几个文件放到工程目录下面即可。