简体   繁体   English

如何在 pqxx7 中使用动态参数执行 sql

[英]How to exec the sql with dynamic params in pqxx7

I want to exec the sql with dynamci params我想用动态参数执行 sql

I can find the codes like the following in pqxx4我可以在 pqxx4 中找到如下代码

work txn(*conn);
pqxx::result r = txn.prepared("insert into mytable (a,b,c,d,e) values (1,2,$1,$2,$3)")(person_name)(age)(sex).exec();
txn.commit();

but I use the pqxx of version 7, the code can't support.但是我用的是7版本的pqxx,代码不支持。

so How to exec the sql with dynamic params in pqxx7?那么如何在 pqxx7 中使用动态参数执行 sql?

using FieldValue = std::variant<int32_t, int64_t, float, double, std::string, bool>

std::string tableName = "mytable";
std::vector<std::string> columNames{"a", "b", "c", "d", "e", ...};
std::vector<FieldValue >{1, "", 2, "", 5L ...};

std::string sql = "INSERT INTO \"" + tableName + "\"(";
for (int i = 0; i < colums.size(); i++)
{
  if (i > 0)
  {
    sql += ", ";
  }
  sql += colums[i];
}
sql += " ) VALUES ( ";
for (int i = 0; i < colums.size(); i++)
{
  if (i > 0)
  {
    sql += ", ";
  }
  sql += "$" + std::to_string(i + 1);
}
sql += " )";

pqxx::connection conn{...};
conn.prepare("test", sql);
pqxx::work work(conn);


how to do?怎么做?

I think what you're looking for is in the Documentation section on Prepared Statements (sorry no link as it keeps changing)我认为您正在寻找的是准备好的声明的文档部分(抱歉没有链接,因为它不断变化)

pqxx::connection conn;
conn.prepare("insert_statement", "insert into mytable(a, b, c, d, e) values (1, 2, $1, $2, $3)");

Then at some later point:然后在稍后的某个时间点:

pqxx::transaction txn(conn);
txn.exec_prepared("insert_statement", field_value3, field_value4, field_value5);

If you're going to be inserting strings use:如果您要插入字符串,请使用:

txn.esc(field_value)

There are various different ways of executing prepared statements but this is something similar to what I currently use with libpqxx 7.x.执行准备好的语句有多种不同的方法,但这与我目前在 libpqxx 7.x 中使用的方法相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM