libpqxx:如何绑定参数数组
libpqxx: How to bind array of parameters
我想尽快在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();
相关文章:
- 为什么 std::绑定错误参数可以成功?
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 绑定到可变参数成员函数
- 如何在 C# 中将带有参数的函数绑定到包中
- 如何在宏中正确转发结构化绑定参数
- std::绑定可变参数模板、绑定参数和占位符
- libpqxx:如何绑定参数数组
- 传递 boost::绑定参数作为参数
- std::绑定参数复制行为
- 绑定参数多于所需的函数,并向其传递明确的参数
- 信号和绑定参数
- 使用尽可能少的代码将非静态方法包装到 std::函数中"this"并绑定参数
- C++sqlite3绑定参数
- c++使用ODBC绑定参数预先确定VARCHAR的长度
- 在SQLite3中绑定参数是如何工作的(最小示例)
- 如何在Postgresql中准备语句和绑定参数
- 如何调试SQLite3中的绑定参数
- 在设置函数指针之前绑定参数
- 使用boost::fusion::for_each时传递/绑定参数
- 使用std::bind分别绑定参数和对象实例