簡體   English   中英

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

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

如何在c++使用pqxx for postgresql在 sql 查詢中執行IN 我有 id 的vector<long>並且我需要更新表faculty_id每一行(將faculty_id設置為一些新值)。 我想避免循環,當我用prepared INSERT語句插入 Faculty 時得到的新值 ( faculty _id)。 是否可以使用 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 中使用類似的方法( 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 + ")";

我理解@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() + "')";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM