c++ - libpqxx 关闭准备好的语句和结果

标签 c++ postgresql libpqxx

我将通过 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 显式关闭结果和准备好的语句以避免内存泄漏?提前致谢

最佳答案

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

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

  • 您不应该重复使用r变量 - 最好在 try 中声明结果对象 block ,因此一旦不需要就会被清除;
  • 您不应该调用C.disconnect()里面try阻止 - 最好只允许 C超出范围。

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

关于c++ - libpqxx 关闭准备好的语句和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14562515/

相关文章:

postgresql - 调试缓慢的 Postgresql 9.3 提交

sql - Postgresql 从 JSON 列中选择

c++ - c_str == string 与 c_str == c_str 的值相等

c++ - 使用 libpq/libpqxx 进行输入清理

c++ - 如何通过 c_str() 库 API 使用 C++ 流。

c++ - 将文本文件加载为多维数组?

c++ - 已删除的构造函数/运算符的可访问性是否重要?

c++ - 当用户定义的 dll 引用另一个用户定义的 dll 时出现链接器错误

sql - postgres - 使用数组值进行透视查询

c++ - 尝试通过 C++ 程序连接到 postgresql