Search code examples
c++postgresqllibpqxx

libpqxx closing prepared statements and results


I will create a connection to a Postgresql db through libpqxx and C++ and then execute several prepared statements, which return results (and I will loop through them). I come from a Java background and the process is:

  1. Open the db connection
  2. prepare the statements
  3. adjust prepared statements params
  4. execute the statements
  5. loop through resultset
  6. close resultset
  7. close prepared statement
  8. close db connection

I have sample code for 1-5 and 8, but I cannot find how to close result object and prepared statement object

Sample code:

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;
}

Do I need to explicitly close result and prepared statement with c++ and libpqxx in order to avoid memory leaks? Thanks in advance


Solution

  • Transaction and result objects are automatically cleaned when they're deleted, which means that they're cleaned when they go out of scope.

    So your code won't leak memory, but it isn't perfect:

    • you should not reuse r variable - it is better to declare result object inside a try block, so it would be cleared as soon as not needed;
    • you should not call C.disconnect() inside try block - it's better to just allow C to go out of scope.

    In C++ you're not supposed to declare variables outside of minimal needed scope - let compiler optimize this for you.