libpqxx:如何绑定参数数组

libpqxx: How to bind array of parameters

本文关键字:绑定 参数 数组 何绑定 libpqxx      更新时间:2023-10-16

我想尽快在postgres表中插入许多参数。

现在我浪费了太多时间来逐个绑定参数。代码看起来几乎是这样的:

pqxx::connection my_connection(c_string);
my_connection.prepare("insert_to_db", "INSERT INTO t (id, name) VALUES ($1, $2));
pqxx::work W(my_connection);
for (int i = 0; i < 10000; i++)
{
  W.prepared("insert_to_db")(i)("Max").exec();
}
W.commit();

如我所见,commit 10 000 个元素需要 0.001 秒甚至更短的时间,但绑定大约需要 10 秒。

我想将所有参数绑定为值数组。如何使用 pqxx 来做到这一点?或者有更好的方法来最小化时间?

尽可能使用 pqxx::p repare::invocation,并在执行前绑定更多值,因为它更稳定且可防止错误,但有一种更快的方法,如下所述。在您的示例中,您每次都执行预准备语句,因此您不必要地与数据库通信。

我。使用调用:

pqxx::nontransaction W(C);
std::string m_insertCommand = "INSERT INTO tableforperftest(column1, column2) VALUES";

unsigned  int m_nCurrentRow = 32767;
for (size_t i = 0; i < m_nCurrentRow; i++)
{
    unsigned int countOf$ = i * 2;
    for (unsigned int i = 0; i < 2; ++i)
    {
        if (i == 0)
        {
            m_insertCommand += "(";
        }
        else
        {
            m_insertCommand += ", ";
        }
        m_insertCommand += "$";
        std::stringstream ss;
        ss << countOf$ + i + 1;
        m_insertCommand += ss.str();
    }
   if(i < m_nCurrentRow - 1)
    m_insertCommand += ") ,";
}
m_insertCommand += ")";
C.prepare("insert_into_db", m_insertCommand);
pqxx::prepare::invocation inv = W.prepared("insert_into_db");
for (size_t i = 0; i < m_nCurrentRow; i++)
{
    inv(i)(i);
}
inv.exec();

第二。使用获取更多参数值的存储过程:

CREATE OR REPLACE FUNCTION insertintoboosted(valuesforinsert TEXT) RETURNS VOID AS
$$ 
BEGIN
     EXECUTE 'INSERT INTO tableforperftestproof(column1, column2) VALUES (' || valuesforinsert || ')';
END;
$$
LANGUAGE plpgsql;

法典:

for (size_t i = 0; i < m_nCurrentRow; i++)
{
    if (i == 0)
        ss  << i << "," << i;
    else
        ss << "(" << i << "," << i;
    if (i < m_nCurrentRow - 1)
        ss << "),";
}
C.prepare("prep2", "select insertintoboosted($1::text)");
W.prepared("prep2")(ss).exec();

第三。每次使用参数绑定和执行:

std::string m_insertCommand3 = "INSERT INTO tableforperftest(column1, column2) VALUES ($1, $2)";
C.prepare("insert_into_db3", m_insertCommand3);
for (size_t i = 0; i < m_nCurrentRow; i++)
{
    W.prepared("insert_into_db3")(i)(i).exec();
}

要将解决方案与 32767 刀片进行比较:

Invocation:                              --> Elapsed:    0.250292s
Stored Proc:                             --> Elapsed:    0.154507s 
Parameter binding + execution each time: --> Elapsed:    29.5566s
pqxx::connection c;
pqxx::work w(c);
c.prepare("prep", "select stored_proc($1::text[])");
auto r = w.prepared("prep")("{v1, v2}").exec();