简体   繁体   English

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

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

How to perform IN in sql query using pqxx in c++ for postgresql ?如何在c++使用pqxx for postgresql在 sql 查询中执行IN I have vector<long> of ids and I need to update every row in table students ( to set faculty_id to some new value).我有 id 的vector<long>并且我需要更新表faculty_id每一行(将faculty_id设置为一些新值)。 I want to avoid loop, new value ( faculty _id) I get when I insert faculty with prepared INSERT statement.我想避免循环,当我用prepared INSERT语句插入 Faculty 时得到的新值 ( faculty _id)。 Is possible at all to pass so iterable structure or create prepared IN query using pqxx ?是否可以使用 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 I have like vector of id of rows which I need to update $1 我喜欢我需要更新的行的 id 向量

Why not something like that ( How to concatenate a std::string and an int? ) in C++11为什么不在 C++11 中使用类似的方法( How to concatenate a std::string and an 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 + ")";

I understand the concerns of @Massa, however I could not find a different solution than the @Alexandros one.我理解@Massa 的担忧,但是我找不到与@Alexandros 不同的解决方案。

So, a bit improvement to this solution can be the use of std::copy所以,这个解决方案的一点改进可以是使用 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() + "')";

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

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