5

How to perform IN in sql query using pqxx in c++ for postgresql ? I have vector<long> of ids and I need to update every row in table students ( to set faculty_id to some new value). I want to avoid loop, new value (faculty_id) I get when I insert faculty with prepared INSERT statement. Is possible at all to pass so iterable structure or create prepared IN query using pqxx ?

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

4

2 回答 2

0

为什么不在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 + ")";
于 2014-05-26T17:52:50.737 回答
0

我理解@Massa 的担忧,但是我找不到与@Alexandros 不同的解决方案。

因此,对这个解决方案的一点改进可以是使用 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() + "')";
于 2020-08-05T09:12:32.010 回答