执行SQL语句并处理结果
向数据库发出执行SQL的请求时,需要使用语句句柄,并调用OCIStmtPrepare和OCIStmtExecute执行查询,服务端执行完成后查询的结果将保存在语句句柄中,使用OCIStmtFetch获取结果。
执行查询 获取结果
调用OCIAllocHandle()函数获取语句句柄,使用OCIStmtPrepare预编译语句,使用OCIDefineByPos绑定缓冲区,然后调用SQLExecute执行查询,最后调用OCIStmtFetch获取结果集。
OCIStmt *stmthp; //语句句柄
text *sqlstmt=(text *)”select C1 from T2”;
if(OCIHandleAlloc ((dvoid *) envhp, (dvoid **) &errhp, OCI_HTYPE_ERROR,
(size_t) 0, (dvoid **) 0))
{
printf("FAILED: OCIHandleAlloc()\n");
return OCI_ERROR
}
int *c1 = (int *) malloc (sizeof(int) * GET_ROWS);
OCIDefine *bndhp[0];
ub4 stmrow, stmrowEx;
OCIParam* colhd = NULL;
int i;
i = ‘+’;
memset(c1, 0, sizeof(int) * GET_ROWS);
/*执行语句*/
OCIStmtPrepare(stmthp, errhp, sqlstmt, strlen((char *)sqlstmt), OCI_NTV_SYNTAX, 0);
if(OCIStmtExecute(svchp, stmthp, errhp, 0, 0, 0, 0, 0))
{
printf(“FAILED: OCIStmtExecute()\n”);
}
/*绑定缓冲区到相对应的列上*/
if(OCIDefineByPos(stmthp, &bndhp[0], errhp, 1
(dvoid *)c1, (sb4)sizeof(int), (ub2)SQLT_INT,
(dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT))
{
printf(“FAILED: OCIDefineByPos()\n”);
return OCI_ERROR;
}
if (OCIDefineArrayOfStruct(bndhp[0], errhp, sizeof(int), 0, 0, 0))
{
printf(“FAILED: OCIDefineArrayOfStruct ()\n”);
return OCI_ERROR;
}
/*获取结果*/
If(OCIStmtFetch(stmthp, errhp, GET_ROWS, OCI_FETCH_NEXT, 0))
{
printf(“FAILED: OCIStmtFetch ()\n”);
return OCI_ERROR;
}
执行插入
要更改数据(执行一个insert,update或者delete),可以使用bind的方式绑定参数后再执行。
调用OCIHandleAlloc申请语句句柄,在语句通过调用OCIStmtPrepare准备完成后,可以通过OCIBindByName(或者OCIBindByPos)绑定参数,再调用OCIStmtExecute执行语句。
OCIStmt *stmthp; //语句句柄
text *sqlstmt=(text *)”insert into T2(C1) values(:a)”;
if(OCIHandleAlloc ((dvoid *) envhp, (dvoid **) &errhp, OCI_HTYPE_ERROR,
(size_t) 0, (dvoid **) 0))
{
printf("FAILED: OCIHandleAlloc()\n");
return OCI_ERROR
}
int custno = 9;
OCIStmtPrepare(stmthp, errhp, sqlstmt, strlen((char *)sqlstmt), OCI_NTV_SYNTAX, 0);
if(OCIBindByName(stmthp, &bnd1p, errhp, (text *) “:a”,
(sb4) -1, (dvoid *) &custno,
(sb4) sizeof(int), SQLT_INT,
(dvoid *) 0, (ub2 *)0, (ub2 *)0, (ub4) 0, (ub4 *) 0,
(ub4) OCI_DEFAULT))
{
printf(“FAILED: OCIBindByName()\n”);
return OCI_ERROR;
}
if(OCIStmtExecute(svchp, stmthp, errhp, 0, 0, 0, 0, 0))
{
printf(“FAILED: OCIStmtExecute()\n”);
}
获取结果
调用OCIStmtFetch来获取执行的结果。
//测试获取 SQL 生成的结果集中的行集
if(OCIStmtFetch(stmthp, errhp, GET_ROWS, OCI_FETCH_NEXT, 0))
printf("FAILED: OCIStmtFetch()\n");