【问题标题】:Variable binding using soci with PL/pgSQL使用带有 PL/pgSQL 的 soci 进行变量绑定
【发布时间】:2018-08-22 09:54:11
【问题描述】:

我正在使用 SOCI 库在 Oracle 和 PostgreSQL 数据库上执行数据库查询。我得到了以下error

无法执行查询。致命错误。错误:绑定消息提供 1 个参数,但准备好的语句“”需要 0 个”

当我绑定一个变量并执行以下 PL/pgSQL 时。但 Oracle 变体工作正常。

try
{
        // This doesn't work
        std::string sql_pg = " \
                               do $$\n \
                               declare\n \
                               n bigint := 1;\n \
                               begin\n \
                               while n <= :1\n \
                               loop\n \
                               insert into ip_table (ip, user) values('0.0.0.1', 'user1');\n \
                               n := n + 1;\n \
                               end loop;\n \
                               end;\n \
                               $$;";

        // This works
        std::string sql_ora = " \
                               declare\n \
                               n number := 1;\n \
                               sql_statement VARCHAR2(500);\n \
                               begin\n \
                               while n <= :1\n \
                               loop\n \
                               sql_statement := q'[insert into ip_table (ip, user) values('0.0.0.1', 'user1')]';\n \
                               execute immediate sql_statement;\n \
                               n := n + 1;\n \
                               end loop;\n \
                               commit;\n \
                               end;";

        int count=4;
        if (session.get_backend_name() == "postgresql")
                session << sql_pg.c_str(), soci::use(count); // error
        else
                session << sql_ora.c_str(), soci::use(count); // works

        std::cout << "executed successfully" << std::endl;
}
catch(const std::exception& err)
{
        std::cout << err.what() << std::endl;
}

我尝试了按位置和按名称进行变量绑定。对 PL/pgSQL 脚本没有任何作用。如果我用一个值替换变量,脚本就可以工作。有什么想法吗?

这个例子可能不适合这个问题。但是想想我是否使用带有变量的if 条件

【问题讨论】:

  • Postgres 中不需要 PL/pgSQL:insert into ip_table (ip, user) select '0.0.0.1', 'user1' from generate_series(1, :1)
  • 是的。这个例子可能不适合这个问题。但是考虑一下我是否使用带有变量的if 条件。

标签: postgresql plpgsql soci variable-binding


【解决方案1】:

你不能在 Postgres 中做到这一点。 DO 命令不允许使用外部参数。您只能在客户端应用参数(注意 SQL 注入)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 2013-11-07
    • 2015-12-31
    • 2021-05-07
    • 2015-06-18
    • 2011-12-10
    • 2018-08-01
    相关资源
    最近更新 更多