首页 > 解决方案 > 使用 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);

标签: postgresqllibpq

解决方案


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);

  }

这是工作!!!


推荐阅读