postgresql - 使用 libpq 准备多行
问题描述
如何使用 PQprepare 使用 libpq 在一行中插入大约 100 行?
我不知道,也许我的参数是错误的......
谢谢你的回复。
const char command[] = "INSERT INTO car (id, name, price, day, time)"
"VALUES($1, $2, $3, $4, $5),"
"VALUES($1, $2, $3, $4, $5),"
"VALUES($1, $2, $3, $4, $5),"
"VALUES($1, $2, $3, $4, $5),"
"VALUES($1, $2, $3, $4, $5);";
int nParams = 5;
char* paramValues[5];
int* paramLengths = new int[5];
int* paramFormats = new int[5];
res = PQprepare(conn, "insertStmt", command, nParams, NULL);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
std::cout << "PQprepare failed:" << PQresultErrorMessage(res) << std::endl;
PQclear(res);
} else {
PQclear(res);
res = PQexecPrepared(conn, "insertStmt", nParams, paramValues, paramLengths,
paramFormats, resultFormat);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
std::cout << "PQexecPrepared failed: " << PQresultErrorMessage(res)
<< std::endl;
}
PQclear(res);
解决方案
const char command[] = "INSERT INTO car (id, name, price, day, time)"
"VALUES($1, $2, $3, $4, $5),"
"($6, $7, $8, $9, $10)";
int nParams = 10;
const char *const paramValues[] = {"2","P", "56", "1999-01-08", "1999-01-08 04:05:06",
"3","P", "56", "1999-01-08", "1999-01-08 04:05:06"};
const int paramLengths[] = {sizeof(int), sizeof(char), sizeof(double), sizeof(int),
sizeof(double),sizeof(int), sizeof(char), sizeof(double), sizeof(int), sizeof(double)};
const int paramFormats[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int resultFormat = 1;
/* PREPARE INSERT */
res = PQprepare(conn, "insertStmt", command, nParams, NULL);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
std::cout << "PQprepare failed:" << PQresultErrorMessage(res) << std::endl;
PQclear(res);
} else {
PQclear(res);
res = PQexecPrepared(conn, "insertStmt", nParams, paramValues, paramLengths,
paramFormats, resultFormat);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
std::cout << "PQexecPrepared failed: " << PQresultErrorMessage(res)
<< std::endl;
}
PQclear(res);
}
这是工作!!!
推荐阅读
- c++ - 如何读取 EXE 字节,存储到 char 数组中,然后将字节写入新的 EXE 文件?
- javascript - 在javascript中第二次随机选择值失败
- javascript - axios 无法提交 Javascript 数组
- c++ - 使用 C++ 从文件中将值输入到数组中
- node.js - 502, Bad Gateway, 我已经使用 express-http-proxy 设置了 wordpress rest api
- javascript - 填写表格时如何使进度条工作
- c# - URL 重写中间件 ASP.Net Core 2.0
- scala - 将 IntelliJ 指向已安装的 Scala
- python - 在 Featuretools 中使用多个训练窗口计算相同的特征
- python - 如何在python中的方法内模拟导入