当前位置:网站首页>Jincang Database OCCI Migration Guide (5. Program Development Example)
Jincang Database OCCI Migration Guide (5. Program Development Example)
2022-08-03 03:32:00 【A thousand sails pass by the side of the sinking boat_】
5. Program development example
Several are provided in this appendix KingbaseES OCCI using the sample program.
连接和断开数据库
执行批量插入
Execute a query statement and get the results
写入 BLOB/CLOB 数据
读取 BLOB/CLOB 数据
获取元信息
Anonymous blocks and cursors
5.1. 连接和断开数据库
#include <iostream>
#include <sys/time.h>
#include <string>
#include <occi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace oracle::occi;
using namespace std;
/* 初始化OCCI环境资源,并创建连接 */
bool connect()
{
/* 数据库的用户名和密码 */
const string szUserName = "system";
const string szUserPwd = "123456";
/* KESthe data source name,位于sys_service.conf中 */
const string szConnection = "KingbaseES";
if(connected)
return true;
/* 第一步,初始化OCCI的ENV环境 */
pEnv = Environment::createEnvironment();
try
{
/* 第二步,在ENVCreated belowKES数据库的OCCI的连接对象 */
pConn = pEnv->createConnection(szUserName, szUserPwd, szConnection);
}
catch (SQLException &ex)
{
/* 捕获OCCIexception and print an error message */
cout << ex.getMessage() << endl;
}
if (NULL == pConn)
{
cout << "Connection Failure" << endl;
return false;
}
cout << "connect Success" << endl;
connected = true;
return true;
}
/* 断开连接,并释放OCCI的环境资源 */
bool disconnect()
{
if(false == connected)
return true;
/* 断开数据库连接 */
pEnv->terminateConnection(pConn);
/* 销毁OCCI的环境资源 */
Environment::terminateEnvironment(pEnv);
delete pEnv;
pConn = NULL;
pEnv = NULL;
cout << "disconnect Success" << endl;
connected = false;
return true;
}5.2. 执行批量插入
/* Defines the number of rows to bulk insert */
#define MAX_ARRAYSIZE 1000
/* 通过OCCIThe loop iteration bound function does bulk inserts */
void iterationDemo()
{
Statement *pStmt = NULL;
ResultSet *pRs = NULL;
char msgBuf[100] = {0};
struct timeval tvBegin, tvEnd;
string strSqlSelect = "select * from gp_dupchk";
string strSqCreate = "create table gp_dupchk(hash_id varchar(32) not null,"
"file_nm varchar(64),"
"cdr_item number(10),"
"call_start_dt number(8) not null,"
"primary key(hash_id) )";
string strSqDrop = "drop table if exists gp_dupchk";
string strSqlInsert = "insert into gp_dupchk values( :1, :2, :3, :4 )";
unsigned int ret =0;
print_bar((char*)__FUNCTION__);
if(!connect())
{
cout<<__FUNCTION__<<" Failed"<<endl;
return;
}
try
{
/* 在OCCICreate a statement object under the connection object */
pStmt = pConn->createStatement();
/* 关联一条SQLstatement to this statement object */
pStmt -> setSQL(strSqDrop);
/* 执行非查询语句 */
pStmt->executeUpdate();
/* Link to anotherSQLstatement to this statement object */
pStmt -> setSQL(strSqCreate);
ret = pStmt->executeUpdate();
pStmt->setSQL(strSqlInsert);
/* Set the maximum number of rows to iterate */
pStmt->setMaxIterations(MAX_ARRAYSIZE);
/* Sets the maximum size of binding parameters */
pStmt->setMaxParamSize(1, 32);
pStmt->setMaxParamSize(2, 64);
pStmt->setMaxParamSize(3, 10);
pStmt->setMaxParamSize(4, 20);
for(int i=0; i<MAX_ARRAYSIZE-1; i++)
{
sprintf(msgBuf, "AAAAAA%d", i);
/* 设置绑定参数 */
pStmt->setString(1, msgBuf);
pStmt->setString(2, "BBBBBB");
pStmt->setInt(3, 1);
pStmt->setNumber(4, Number(2));
/* added to the iterator */
pStmt->addIteration();
}
/*
* Add the last line of bind parameters
* 不需要addInteration(),
* 如果调用,will insert oneNULL行
*/
pStmt->setString(1, "GGGGGG");
pStmt->setString(2, "HHHHHH");
pStmt->setInt(3, 7);
pStmt->setNumber(4, Number(8));
gettimeofday(&tvBegin, NULL);
/* 执行批量插入 */
ret = pStmt->executeUpdate();
/* Get the actual number of affected rows */
if(pStmt->getUpdateCount()!= MAX_ARRAYSIZE ){
cout << "batch insert failed!
Expect:"<< MAX_ARRAYSIZE << "
but getUpdateCount: " << pStmt->getUpdateCount() << endl;
}else{
cout << "batch insert success" << endl;
}
gettimeofday(&tvEnd, NULL);
printf("batch insert time: [%ld]\n",
(tvEnd.tv_sec - tvBegin.tv_sec) * 1000 +
(tvEnd.tv_usec - tvBegin.tv_usec) / 1000);
cout << "insert getUpdateCount(): " << pStmt->getUpdateCount() << endl;
/* Release statement object resources */
pConn -> terminateStatement(pStmt);
pStmt = NULL;
}
catch ( SQLException &ex)
{
cout << "ErrorCode: " << ex.getErrorCode() << endl;
cout << ex.getMessage() << endl;
cout << "insert getUpdateCount(): " << pStmt->getUpdateCount() << endl;
}
disconnect();
cout << "iterationDemo Success" << endl;
}5.3. Execute a query statement and get the results
/* 通过OCCIExecute the query and get the returned result set */
void selectDemo()
{
Statement *pStmt = NULL;
ResultSet *pRs = NULL;
string strSqlSelect = "select * from t_occi_selectDemo";
string strSqCreate = "create table t_occi_selectDemo(c_id int,
c_name varchar(40),
c_number numeric(6,2),
c_number8 numeric(15,8))";
string strSqDrop = "drop table IF EXISTS t_occi_selectDemo";
string strSqlinsert1 = "insert into t_occi_selectDemo
values(1,'Jack',11.11,33.33333333)";
string strSqlinsert2 = "insert into t_occi_selectDemo
values(2,'Tom',22.22,44.44444444)";
print_bar((char*)__FUNCTION__);
if(!connect())
{
cout<<__FUNCTION__<<" Failed"<<endl;
return;
}
try
{
/* 准备表和数据 */
pStmt = pConn->createStatement();
pStmt -> setSQL(strSqDrop);
pStmt->executeUpdate();
pStmt -> setSQL(strSqCreate);
pStmt->executeUpdate();
pStmt->executeUpdate(strSqlinsert1);
pStmt->executeUpdate(strSqlinsert2);
/* 关联查询语句 */
pStmt -> setSQL(strSqlSelect);
/* 执行查询,And get the returned result set object */
pRs = pStmt->executeQuery();
/* 遍历结果集 */
while ( pRs -> next())
{
/* Get the value of each field in the result set */
cout << pRs->getInt(1) << " "
<< pRs->getString(2) << " " << pRs->getFloat(3)
<< " " << pRs->getFloat(4) <<endl;
}
/* 关闭结果集对象 */
pStmt -> closeResultSet(pRs);
pRs = NULL;
/* Clear tables and data */
pStmt->execute(strSqDrop);
pConn -> terminateStatement(pStmt);
pStmt = NULL;
}
catch ( SQLException &ex)
{
cout << ex.getMessage() << endl;
}
disconnect();
cout << "selectDemo Success" << endl;
}5.4. 写入 BLOB/CLOB 数据
/* 通过OCCI写入大对象 */
void lobWriteDemo()
{
Statement *pStmt = NULL;
ResultSet *pRs = NULL;
unsigned int amt, offset, len, act_read_count;
int not_read_count;
unsigned char buff[READ_BUFSIZE];
FILE *fp = NULL;
/* 通过for updatestatement to get a large object */
string strSqlSelect = "select * from t_lob for update";
string strSqCreate = "create table t_lob(b blob, c1 clob, c2 nclob)";
string strSqDrop = "DROP TABLE IF EXISTS t_lob";
string strSqlinsert = "INSERT INTO T_LOB
VALUES(EMPTY_BLOB(),
EMPTY_CLOB(),
EMPTY_NCLOB())";
unsigned char * cbuff = (unsigned char *)malloc(READ_BUFSIZE * 512 + 1);
if(NULL == cbuff)
{
printf("unsigned char * cbuff = malloc(READ_BUFSIZE * 512 + 1);
failed\n");
return;
}
print_bar((char*)__FUNCTION__);
if(!connect())
{
cout<<__FUNCTION__<<" Failed"<<endl;
return;
}
try
{
pStmt = pConn->createStatement();
pStmt -> setSQL(strSqDrop);
pStmt->executeUpdate();
pStmt -> setSQL(strSqCreate);
pStmt->executeUpdate();
pStmt -> setSQL(strSqlinsert);
pStmt->executeUpdate();
/* 通过select for updateGet the large object and lock the row */
pStmt -> setSQL(strSqlSelect);
pRs = pStmt->executeQuery();
while (pRs->next())
{
/* 从结果集中获取OCCI的Blob对象 */
Blob blob = pRs->getBlob(1);
if(blob.isNull())
{
cout << "Null Blob" << endl;
}
else
{
/* 以读写方式打开Blob对象 */
blob.open(OCCI_LOB_READWRITE);
offset = 1;
not_read_count = 1548;
/* Open a local disk file */
fp = fopen("blob_in", "rb");
/*
* 循环读取文件中的数据,
* 每次最多读取READ_BUFSIZE的块,
* Write the data read each timeblob对象中
*/
while (not_read_count > 0)
{
not_read_count -= READ_BUFSIZE;
if (not_read_count < 0)
{
act_read_count = READ_BUFSIZE + not_read_count;
}
else
{
act_read_count = READ_BUFSIZE;
}
memset(buff, 0, act_read_count);
fread(buff, 1, act_read_count, fp);
/*
* 写入到blob大对象中
* amtis the size expected to be written this time
* buffis the data to be written
* act_read_count是buff的大小
* offsetis the offset written
*/
amt = act_read_count;
act_read_count = blob.writeChunk(amt, buff, act_read_count, offset);
if (act_read_count > 0)
{
offset += amt;
}
}
/* 获取blob的数据长度 */
len = blob.length();
/* 关闭blob对象 */
blob.close();
fclose(fp);
cout <<"write " << len << " into blob" << endl;
}
/* Clob的写入操作,和Blob类似 */
Clob clob1 = pRs->getClob(2);
if(clob1.isNull())
{
cout << "Null Clob" << endl;
}
else
{
clob1.open(OCCI_LOB_READWRITE);
offset = 1;
not_read_count = 1483407;
fp = fopen("clob1_in.txt", "r");
while (not_read_count > 0)
{
if (not_read_count > READ_BUFSIZE * 512)
act_read_count = READ_BUFSIZE * 512;
else
act_read_count = not_read_count;
memset(cbuff, 0, READ_BUFSIZE * 512 + 1);
fread(cbuff, 1, act_read_count, fp);
cbuff[act_read_count] = '\0';
/* Write it in the locator */
amt = act_read_count;
clob1.writeChunk(amt, cbuff, act_read_count + 1, offset);
offset += amt;
not_read_count -= act_read_count;
}
len = clob1.length();
clob1.close();
fclose(fp);
cout <<"write " << len << " into clob1" << endl;
}
Clob clob2 = pRs->getClob(3);
if(clob2.isNull())
{
cout << "Null Clob" << endl;
}
else
{
offset = 1;
#if defined(WIN32)
not_read_count = 4477;
fp = fopen("clob2_in_gb2312.txt", "r");
#else
not_read_count = 4500;
fp = fopen("clob2_in.txt", "r");
#endif
while (not_read_count > 0)
{
if (not_read_count > READ_BUFSIZE)
act_read_count = READ_BUFSIZE;
else
act_read_count = not_read_count;
memset(cbuff, 0, READ_BUFSIZE + 1);
fread(cbuff, 1, act_read_count, fp);
cbuff[act_read_count] = '\0';
/* Write it in the locator */
amt = act_read_count;
clob2.write(amt, cbuff, act_read_count + 1, offset);
offset += amt;
not_read_count -= act_read_count;
}
len = clob2.length();
fclose(fp);
cout <<"write " << len << " into clob2" << endl;
}
}
pStmt -> closeResultSet(pRs);
pRs = NULL;
pConn -> terminateStatement(pStmt);
pStmt = NULL;
}
catch ( SQLException &ex)
{
cout << ex.getMessage() << endl;
cout << "lobWriteDemo caught exception!!!" << endl;
}
disconnect();
free(cbuff);
cout << "lobWriteDemo Success" << endl;
}5.5. 读取 BLOB/CLOB 数据
/* 通过OCCI读取大对象 */
void lobReadDemo()
{
Statement *pStmt = NULL;
ResultSet *pRs = NULL;
unsigned int amt, offset, len, act_read_count;
unsigned char buff[READ_BUFSIZE];
FILE *fp = NULL;
string strSqlSelect = "select * from t_lob";
print_bar((char*)__FUNCTION__);
if(!connect())
{
cout<<__FUNCTION__<<" Failed"<<endl;
return;
}
try
{
pStmt = pConn->createStatement();
pStmt -> setSQL(strSqlSelect);
pRs = pStmt->executeQuery();
while (pRs->next())
{
Blob blob = pRs->getBlob(1);
if(blob.isNull())
{
cout << "Null Blob" << endl;
}
else
{
/* Open the large object as read-only */
blob.open(OCCI_LOB_READONLY);
/* Get the large object length */
len = blob.length();
cout << "blob: len = " << len << endl;
amt = READ_BUFSIZE;
/* 将BLOB数据读取到文件中 */
offset = 1;
fp = fopen("blob_out", "wb");
/* Large object data is read in a chunked loop */
while(1)
{
memset((dvoid *)buff, 0, READ_BUFSIZE);
/* Reads a block of data of the specified size from the large object offset */
act_read_count = blob.read(amt, buff, READ_BUFSIZE, offset);
if(act_read_count > 0)
{
fwrite(buff, act_read_count, 1, fp);
offset += act_read_count;
}
else
{
break;
}
}
blob.close();
fclose(fp);
}
/* Clob 的读取,和Blob类似 */
Clob clob1 = pRs->getClob(2);
if(clob1.isNull())
{
cout << "Null Clob" << endl;
}
else
{
clob1.open(OCCI_LOB_READONLY);
len = clob1.length();
cout << "clob1: len = " << len << endl;
amt = READ_BUFSIZE - 1;
/* 将CLOB数据读取到文件中 */
offset = 1;
fp = fopen("clob1_out.txt", "wb");
while(1)
{
memset((dvoid *)buff, 0, READ_BUFSIZE);
act_read_count = clob1.read(amt, buff, READ_BUFSIZE, offset);
if(act_read_count > 0)
{
fwrite(buff, act_read_count, 1, fp);
offset += act_read_count;
}
else
{
break;
}
}
clob1.close();
fclose(fp);
}
Clob clob2 = pRs->getClob(3);
if(clob2.isNull())
{
cout << "Null Clob" << endl;
}
else
{
clob2.open(OCCI_LOB_READONLY);
len = clob2.length();
cout << "clob2: len = " << len << endl;
amt = READ_BUFSIZE - 1;
/* 将CLOB数据读取到文件中 */
offset = 1;
fp = fopen("clob2_out.txt", "wb");
while(1)
{
memset((dvoid *)buff, 0, READ_BUFSIZE);
act_read_count = clob2.read(amt, buff, READ_BUFSIZE, offset);
if(act_read_count > 0)
{
fwrite(buff, act_read_count, 1, fp);
offset += act_read_count;
}
else
{
break;
}
}
clob2.close();
fclose(fp);
}
}
pStmt -> closeResultSet(pRs);
pRs = NULL;
pConn -> terminateStatement(pStmt);
pStmt = NULL;
}
catch ( SQLException &ex)
{
cout << ex.getMessage() << endl;
cout << "lobReadDemo caught exception!!!" << endl;
}
disconnect();
cout << "lobReadDemo Success" << endl;
}5.6. 获取元信息
void MetaDataDemo()
{
Statement *pStmt = NULL;
string strSqCreate = "create table t_occi_MeTaDataDemo(
c_id int,c_name varchar(20),
c_date date,c_timestamp timestamp)";
string strSqDrop = "drop table if EXISTS t_occi_MeTaDataDemo";
print_bar((char*)__FUNCTION__);
if(!connect())
{
cout<<__FUNCTION__<<" Failed"<<endl;
return;
}
try
{
/* 准备表和数据 */
pStmt = pConn->createStatement();
pStmt -> setSQL(strSqDrop);
pStmt->executeUpdate();
pStmt -> setSQL(strSqCreate);
pStmt->executeUpdate();
/* Get the meta information of the specified table in the database */
MetaData meta = pConn->getMetaData(
"T_OCCI_METADATADEMO",MetaData::PTYPE_TABLE);
/* 获取对象类型 */
if(meta.getInt(MetaData::ATTR_PTYPE) ==MetaData::PTYPE_TABLE)
{
cout << "it is table" << endl;
/* Get field attribute information for a table */
vector<MetaData> tab_col_list = meta.getVector(
MetaData::ATTR_LIST_COLUMNS);
/* Traverse to get the meta information of each field */
std::vector<MetaData>::iterator p;
unsigned int i;
p = tab_col_list.begin();
for(i = 0; i < tab_col_list.size(); i++)
{
/* Get the bullet's name and type */
cout << "ATTR_NAME " << i << " "
<< p->getString(MetaData::ATTR_NAME);
cout << " " << p->getInt(MetaData::ATTR_DATA_TYPE) << endl;
p++;
}
}
else
cout << "it is not table" << endl;
pStmt->execute(strSqDrop);
pConn -> terminateStatement(pStmt);
pStmt = NULL;
}
catch ( SQLException &ex)
{
cout << "error:" << ex.getMessage() << endl;
}
disconnect();
cout << "MetaDataDemo Success" << endl;
}5.7. Anonymous blocks and cursors
void PackageCursorNoBeginDemo()
{
print_bar((char*)__FUNCTION__);
if(!connect())
{
cout<<__FUNCTION__<<" Failed"<<endl;
return;
}
cout << "callproc - invoking a PL/SQL procedure having OUT Cursor ";
cout << "parameters" << endl;
OraText *sqldropTable = (OraText *)"drop table if exists room";
OraText *sqlcreateTable = (OraText *)"create table room (
id int,name varchar(20));";
OraText *sqlInsert = (OraText *)"insert into room values (1,'qweqwe'),
(2,'asdasd'),
(3,'zxczxc');";
OraText *sqlPackageHead = (OraText *)
"CREATE OR REPLACE PACKAGE PUBLIC.CURSOR_PKG AS "
"cur1 REFCURSOR;"
"PROCEDURE fa_out_refcursor(a int,c inout refcursor);"
"END;";
OraText *sqlPackageBody = (OraText *)
"CREATE OR REPLACE PACKAGE BODY PUBLIC.CURSOR_PKG AS "
"PROCEDURE fa_out_refcursor(a int,c inout refcursor) as "
"begin "
"open cur1 FOR SELECT * FROM room where id > a; "
"c := cur1;"
"end;"
"END;";
OraText * sql_out_refcursor = (OraText*)"begin public.cursor_pkg.fa_out_refcursor
(:int_,:stmt_recursor);end;";
Statement *stmt = pConn->createStatement();
try{
/* Active and standby tables,存储过程,数据 */
cout << "Create table and proc :" << sqlPackageHead << endl;
stmt->setSQL((char*)sqldropTable);
stmt->execute();
stmt->setSQL((char*)sqlcreateTable);
stmt->execute();
stmt->setSQL((char*)sqlInsert);
stmt->execute();
stmt->setSQL((char*)sqlPackageHead);
stmt->execute();
stmt->setSQL((char*)sqlPackageBody);
stmt->execute();
/* 绑定INOUT参数,执行匿名块 */
cout << "Executing the block :" << sql_out_refcursor << endl;
stmt->setSQL((char*)sql_out_refcursor);
stmt->setInt (1, 1);
stmt->registerOutParam (2, OCCICURSOR);
int updateCount = stmt->executeUpdate ();
cout << "Update Count:" << updateCount << endl;
/* Get the cursor returned by the anonymous block */
ResultSet* rs_cursor = stmt->getCursor (2);
/* Traverse the result set data in the cursor */
while(rs_cursor->next())
{
cout << "Printing the OUT cursor:" << endl;
cout << "Cursor's Col1: " << rs_cursor->getInt(1) << endl;
cout << "Cursor's Col2: " << rs_cursor->getString(2) << endl;
}
stmt->closeResultSet(rs_cursor);
pConn->terminateStatement (stmt);
cout << "occiproc - done" << endl;
if(!disconnect())
{
cout<<__FUNCTION__<<" Failed"<<endl;
return;
}
}
catch (SQLException ex){
cout << ex.getMessage() << endl;
}
}边栏推荐
- VS中使用BugTrap定位程序崩溃点
- LVS负载均衡群集及部署LVS-NAT实验
- 密码学的基础:X.690和对应的BER CER DER编码
- 基于 Cyclone IV 在 Quartus 中配置 IP 核中的 PLL、RAM 与 FIFO 的详细步骤及仿真验证
- 【原创】Auto.js get和post 案例
- MySQL-多表查询
- vant-field中colon属性为true报错
- leetcode:149. 直线上最多的点数
- vsftp容器搭建+go开发web用户管理界面(更新于2022.02.23)
- Incorrect datetime value: '2022-01-01' for function str_to_date
猜你喜欢
随机推荐
程序员写代码日常 | 每日趣闻
Mysql-如何进行慢SQL查询
【obs】启动推流失败 : Output.StartStreamFailed 调用流程
QCheckBox、margin、border、pandding、QHoxLayout、QSplitter、QSpacerItem
【静态类型和动态类型 编译检查和运行检查 Objective-C中】
ROS2自学笔记:机器视觉基础
【TA-霜狼_may-《百人计划》】美术2.5 模型常见问题及规范
ClickHouse—入门
【云原生】服务行业案例-不可预测的并发场景解决方案
05-分布式计算框架
leetcode:153. 寻找旋转排序数组中的最小值
用 SQL 做数据分析的十大常用功能,附面试原题解答!!
七夕??继续肝文章才是正道!!Auto.js 特殊定位控件方法
ClickHouse数据类型
SqlSession [[email protected]]
compose 位移视图
Redshift贴logo的方法
钻石基础知识介绍
List<Object>转List<User>:
Kotlin 乘法、我怎么越乘越小?








