批处理函数
libpq提供PQexecParamsBatch接口实现批处理功能,比PQexecParams接口多了nBatch参数,参数说明如下:
函数 | 说明 |
---|---|
PGconn *conn | 连接句柄 |
const char *command | SQL文本串 |
int nParams | 参数个数 |
int nBatch | 批量操作数 |
const Oid *paramTypes | 绑定参数类型 |
const char * const *paramValues | 绑定参数的值 |
const int *paramLengths | 参数长度 |
const int *paramFormats | 参数格式(文本或二进制) |
int resultFormat | 返回结果格式(文本或二进制) |
示例
#include <stdio.h>
#include <stdlib.h>
#include "libpq-fe.h"
static void
exit_nicely(PGconn *conn)
{
PQfinish(conn);
exit(1);
}
int main(int argc, char **argv)
{
const char *conninfo;
PGconn *conn;
PGresult *res;
int i;
conninfo = "host = localhost user = libpq password = Aa@123 dbname = vastbase port =25638";
/* Make a connection to the database */
conn = PQconnectdb(conninfo);
/* Check to see that the backend connection was successfully made */
if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "%s", PQerrorMessage(conn));
exit_nicely(conn);
}
res = PQexec(conn, "drop table if exists test;create table test(id integer,name varchar(50));");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "sql failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
else
{
printf("sql success\n");
}
PQclear(res);
const char command[] = "INSERT INTO test (id, name)"
"VALUES($1::integer, $2::varchar(50))";
int nParams = 2;
int nBatchCount=4;
const Oid paramTypes[] = {23,1043};
int binaryVal1 = htonl(1);
int binaryVal2 = htonl(2);
int binaryVal3 = htonl(3);
int binaryVal4 = htonl(4);
const char *const paramValues[][2]={{(const char *)&binaryVal1,"123"},
{(const char *)&binaryVal2,"234"},
{(const char *)&binaryVal3,"345"},
{(const char *)&binaryVal4,"456"}};
const int paramLengths[][2] = {{sizeof(int), 3},{sizeof(int), 3},{sizeof(int), 3},{sizeof(int), 3}};
const int paramFormats[] = {1, 1};
int resultFormat = 0;
printf("-----test batch insert -----\n");
res = PQexecParamsBatch(conn, /*连接句柄*/
command, /* SQL文本串 */
nParams , /* 参数个数*/
nBatchCount, /* 批量操作数*/
paramTypes, /*绑定参数类型*/
paramValues[0], /*绑定参数的值*/
paramLengths[0], /* 参数长度*/
paramFormats, /* 参数格式(文本或二进制) */
resultFormat); /* 返回结果格式(文本或二进制) */
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "batch insert failed: %s", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
else
{
printf("batch insert success\n");
}
PQclear(res);
printf("-----print result -----\n");
res = PQexec(conn, "select * from test;");
for (i = 0; i < PQntuples(res); i++)
{
const char* id = NULL;
const char* name = NULL;
id = PQgetvalue(res, i, 0);
name = PQgetvalue(res, i, 1);
printf("id = %s, name = %s \n", id, name);
}
PQclear(res);
PQfinish(conn);
return 0;
}