【问题标题】:libpqxx closing prepared statements and resultslibpqxx 结束准备好的语句和结果
【发布时间】:2013-01-28 12:54:51
【问题描述】:

我将通过 libpqxx 和 C++ 创建到 Postgresql 数据库的连接,然后执行几个准备好的语句,这些语句返回结果(我将循环遍历它们)。我来自Java背景,过程是:

  1. 打开数据库连接
  2. 准备报表
  3. 调整准备好的语句参数
  4. 执行语句
  5. 遍历结果集
  6. 关闭结果集
  7. 关闭准备好的语句
  8. 关闭数据库连接

我有 1-5 和 8 的示例代码,但我找不到如何关闭结果对象和准备好的语句对象

示例代码:

connection C("dbname=mydbname user=postgres password=mypass hostaddr=127.0.0.1 port=5432");
string tableName("mydbtable");
if (C.is_open()) {
    cout << "We are connected to " << C.dbname() << endl;
} else {
    cout << "We are not connected!" << endl;
}

result r;
try {
    const std::string sql =
            "SELECT * FROM " + tableName + " WHERE sn_autoinc10 = $1";
    C.prepare("find", sql);
    //C.prepare("findtable", ) ("integer");
    work W(C);
    r = W.prepared("find")(0).exec();
    for (int rownum = 0; rownum < r.size(); ++rownum) {
        const result::tuple row = r[rownum];
        for (int colnum = 0; colnum < row.size(); ++colnum) {
            const result::field myField = row[colnum];
            std::cout << myField.c_str() << ' ';
        }
        std::cout << std::endl;
    }
    C.disconnect();
} catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
}

我是否需要使用 c++ 和 libpqxx 显式关闭结果和准备好的语句以避免内存泄漏?提前致谢

【问题讨论】:

    标签: c++ postgresql libpqxx


    【解决方案1】:

    事务和结果对象在被删除时会被自动清理,这意味着它们会在超出范围时被清理。

    所以你的代码不会泄漏内存,但它不是完美

    • 您不应该重复使用r 变量 - 最好在try 块内声明结果对象,以便在不需要时将其清除;
    • 您不应在 try 块内调用 C.disconnect() - 最好只允许 C 超出范围。

    在 C++ 中,您不应该在所需范围之外声明变量 - 让编译器为您优化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-27
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2021-08-02
      • 1970-01-01
      • 2019-07-16
      相关资源
      最近更新 更多