如何在postgresql的c++中使用pqxx在sql查询中执行IN

How to perform IN in sql query using pqxx in c++ for postgresql?

本文关键字:sql pqxx 查询 执行 IN postgresql c++      更新时间:2023-10-16

如何在sql查询中使用pqxxc++中为postgresql执行IN ?我有vector<long>的id,我需要更新表学生中的每一行(将faculty_id设置为一些新值)。我想避免循环,新值(faculty _id)我得到当我插入教师与prepared INSERT语句。是否有可能传递可迭代结构或使用pqxx创建prepared IN查询?

void prepareChangeFaculty(connection_base &c){
    const std::string sql =
      "UPDATE students SET faculty_id=$2 WHERE id IN $1"; // here is a problem
    c.prepare("change_faculty", sql);
}

$1我有一个向量id的行我需要更新

为什么在c++ 11

中没有类似的东西(如何连接std::string和int?)
string a="";
for (int k=0;k<myVector.size();k++){
    a += string(myVector[k]);
    if (k<myVector.size()-1){
        a += ",";
    }
}
std::string sql = "UPDATE students SET faculty_id=$2 WHERE id IN (" + a + ")";

我理解@马萨的担忧,但是我找不到一个比@亚历山德罗斯不同的解决方案。

因此,可以使用std::copy 对这个解决方案进行一点改进
std::stringstream params;
std::copy(
    myVector.begin(), myVector.end(),
    std::ostream_iterator<std::string>(params, ","));
std::string sql = "UPDATE students SET faculty_id=$2 WHERE id IN ('"
    + params.str() + "')";