连接池
连接池是多个会话使用一组(池)可重复使用的物理连接来平衡负载。
此功能的一个用途是在服务端从数据库服务器获得多个并发的数据请求时,应用程序可以在应用程序初始化期间在每个环境中创建一个池(或一组池)。
连接池本身通常配置有物理连接的共享池,转换为包含相同数量的专用服务器进程的后端服务器池。
在下面便是建立连接池及其使用。
//创建池子
OCICPool *poolhp;
if(OCIHandleAlloc((void *) envhp, (void **) &poolhp, OCI_HTYPE_CPOOL, (size_t) 0, (void **) 0))
{
report_error(errhp);
printf("FAILED: OCIHandleAlloc()\n");
return OCI_ERROR;
}
char *poolName = NULL;
int poolNameLen = 0;
if(OCIConnectionPoolCreate(envhp,errhp, poolhp,
(dvoid *)&poolName, &poolNameLen,
"Test8",strlen("Test8"),
(ub4) 2, (ub4) 4, (ub4) 1,
(text *)username,strlen(username),
(text *)password,strlen(password),
OCI_DEFAULT))
{
report_error(errhp);
printf("FAILED: OCIConnectionPoolCreate()\n");
return OCI_ERROR;
}
//第一个用户
static OCIServer *svrhp = (OCIServer *)0;
OCIHandleAlloc(envhp, (dvoid **)&svrhp, OCI_HTYPE_SERVER, (size_t)0, (dvoid **)0);
OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, (dvoid *)svrhp, (ub4)0, OCI_ATTR_SERVER, errhp);
if (OCIServerAttach(svrhp, errhp, (text *)poolName, (sb4)strlen((char *)poolName), OCI_CPOOL))
{
report_error(errhp);
printf("FAILED: OCIServerAttach()\n");
return OCI_ERROR;
}
OCIHandleAlloc((void *)envhp, (void **)&usrhp, (ub4)OCI_HTYPE_SESSION, (size_t)0, (void **)0);
OCIAttrSet((void *)usrhp, (ub4)OCI_HTYPE_SESSION,(text *)username,strlen(username), OCI_ATTR_USERNAME, errhp);
OCIAttrSet((void *)usrhp, (ub4)OCI_HTYPE_SESSION, (text *)password,strlen(password), OCI_ATTR_PASSWORD, errhp);
if(OCISessionBegin(svchp, errhp, usrhp, OCI_CRED_RDBMS, OCI_DEFAULT))
{
printf("FAILED: OCISessionBegin()\n");
report_error(errhp);
return OCI_ERROR;
}
OCIAttrSet((void *)svchp, (ub4)OCI_HTYPE_SVCCTX, (void *)usrhp, (ub4)0,OCI_ATTR_SESSION,errhp);
//测试
text *sqlstmt=(text *)"insert into t2(c1,c4) values(1,'111')";
//测试准备一条SQL
if(OCIStmtPrepare(stmthp, errhp, sqlstmt, strlen((char *)sqlstmt),
OCI_NTV_SYNTAX, 0))
{
printf("FAILED: OCIStmtPrepare()\n");
report_error(errhp);
return OCI_ERROR;
}
//测试SQL执行
if(OCIStmtExecute(svchp, stmthp, errhp, 1, 0, 0, 0, 0))
{
report_error(errhp);
printf("FAILED: OCIStmtExecute()\n");
return OCI_ERROR;
}
if(OCITransCommit(svchp,errhp,0))
{
report_error(errhp);
printf("FAILED: OCITransCommit()\n");
return OCI_ERROR;
}
//测试退出
if(OCISessionEnd(svchp,errhp,usrhp,OCI_DEFAULT)){
printf("FAILED: OCISessionEnd()\n");
report_error(errhp);
return OCI_ERROR;
}
if (OCIServerDetach(svrhp, errhp, OCI_DEFAULT))
{
printf("FAILED: OCIServerDetach()\n");
report_error(errhp);
return OCI_ERROR;
}
//销毁第一个池子
if(OCIConnectionPoolDestroy(poolhp, errhp, OCI_DEFAULT))
{
printf("FAILED: OCIConnectionPoolDestroy()\n");
report_error(errhp);
return OCI_ERROR;
}
if(OCIHandleFree((void *)poolhp, OCI_HTYPE_CPOOL))
{
printf("FAILED: OCIHandleFree()\n");
report_error(errhp);
return OCI_ERROR;
}