c++ - 如何在 libpqxx/C++ 准备好的 SQL 语句中将参数绑定(bind)在引号内

标签 c++ postgresql prepared-statement postgis libpqxx

我有一个 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)',因为引号内的参数是文本,所以绑定(bind)参数失败。

我不知道如何修复该错误。

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

最佳答案

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

尝试

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

关于c++ - 如何在 libpqxx/C++ 准备好的 SQL 语句中将参数绑定(bind)在引号内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53735143/

相关文章:

c++ - int64_t 的定义

c++ - 在 Directx 11 中加载 ColorMap 时的文件路径

sql - PostgreSQL 中的分区表

mysql - 在mysql动态存储过程中,是否需要@var来构建准备好的语句?

php - mysqli 在函数内准备好语句

c++ - 将 Nim Anon 函数导出到 C++

c++ - 用户定义的文字为 C++ 添加了哪些新功能?

ruby-on-rails - 带有嵌套表的 ActiveRecord 查询

sql - 当只有某些行是有效的正则表达式时,Postgres : select using column as regex,

java - SQLException : Before start of result set