Search code examples
c++postgresqlprepared-statementpostgislibpqxx

How to bind parameters inside quotes in prepared SQL statement for libpqxx / C++


I have a PostGIS extended PotgreSQL database, and I would like to know how to use pqxx::connection_base::prepare to create an SQL statement with a PostGIS function such as st_distance().

When I query the SQL statemtent to PostgreSQL like this:

database_name=# select st_geomfromtext('POINT(50.0 90.0)', 4326);

I get the response:

                  st_geomfromtext
----------------------------------------------------
 0101000020E610000000000000000049400000000000805640

How to get the above code on libpqxx with C++?

I have tried:

#include <iostream>
#include <pqxx/pqxx>

int main()
{
    try {
        pqxx::connection conn("dbname=xxx user=yyy password=zzz");
        pqxx::work xaction(conn);

        conn.prepare(
            "text to geometry point",
            "select st_geomfromtext('POINT($1 $2)', 4326);"
        );
        pqxx::result selected = xaction.prepared("text to geometry point")(50.0)(90.0).exec();

        for (auto row : selected) {
            for (auto col : row) {
                std::cout << col.c_str() << "\t";
            }
            std::cout << "\n";
        }
        std::cout << std::endl;
        conn.disconnect();
    }
    catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        return 1;
    }
    return 0;
}

But got the error:

ERROR:  bind message supplies 2 parameters, but prepared statement "text to geometry point" requires 0

libpqxx may cannot parse 'POINT($1 $2)' because the parameters inside quotes as text, so failed to bind parameter.

I have not idea to fix the error.

This is the simple example what I want to do. I need to use pqxx::connection_base::prepare in actual work.


Solution

  • The $1 is not interpreted as a parameter, but as a string literal, because it is inside single quotes.

    Try

    'POINT(' || $1 || ' ' || $2 || ')'