【问题标题】:How to bind parameters inside quotes in prepared SQL statement for libpqxx / C++如何在为 libpqxx / C++ 准备的 SQL 语句中的引号内绑定参数
【发布时间】:2019-05-13 02:13:57
【问题描述】:

我有一个 PostGIS 扩展 PotgreSQL 数据库,我想知道如何使用 pqxx::connection_base::prepare 创建带有 PostGIS 函数的 SQL 语句,例如 st_distance()

当我像这样向 PostgreSQL 查询 SQL 语句时:

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

我得到了回应:

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

如何用C++在libpqxx上获取上述代码?

我试过了:

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

但得到了错误:

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

libpqxx 可能无法解析'POINT($1 $2)',因为引号内的参数是文本,所以绑定参数失败。

我不知道如何修复错误。

这是我想做的简单示例。我需要在实际工作中使用pqxx::connection_base::prepare

【问题讨论】:

  • 我按照Laurenz的评论将SQL语句从"select st_geomfromtext('POINT($1 $2)', 4326);"更改为"select st_geomfromtext('POINT(' || $1 || ' ' || $2 || ')', 4326);",并得到了正确的响应。谢谢。

标签: c++ postgresql prepared-statement postgis libpqxx


【解决方案1】:

$1 不被解释为参数,而是作为字符串文字,因为它在单引号内。

试试

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多