pqxx调用PostgreSQL存储过程需改写为RETURNS TABLE或RETS SETOF并用SELECT * FROM调用;不可直接获取OUT参数,避免保存row/field引用,NULL值须先is_null()再as(),事务失败后须新建连接。
如何用 pqxx 绑定参数调用 PostgreSQL 存储过程 pqxx 不支持类似 JDBC 的命名参数(如:nameprepare()exec_params()LANGUAGE plpgsqlINOUTOUTSELECTRETURNS TABLE(...)RETURNS SETOF recordSELECT * FROM my_proc(...)CALLOUTexec("CALL my_proc(...)")exec("FETCH ALL IN \"my_cursor\"")RETURN NEXTCREATE OR REPLACE FUNCTION get_users_by_age(min_age INT)
RETURNS TABLE(id INT, name TEXT, created_at TIMESTAMPTZ) AS $$
BEGIN
RETURN QUERY SELECT u.id, u.name, u.created_at
FROM users u WHERE u.age >= min_age;
END;
$$ LANGUAGE plpgsql;auto txn = conn.transaction();
auto rs = txn.exec_params("SELECT * FROM get_users_by_age($1)",
pqxx::binarystring{min_age});resultrowfieldtransactionconnectionrowfieldtransactionresultrow["col_name"].c_str()const char*std::stringintfor (const auto &row : rs) {
int id = row["id"].as();
std::string name = row["name"].as();
auto ts = row["created_at"].as();
} as() pqxx::conversion_erroris_null()as() row["col"].is_null()as() as() as<:optional>>()as<:chrono::system_clock::time_point>()as<:string>()if (!row["score"].is_null()) {
float score = row["score"].as();
} else {
// 处理 NULL 分数逻辑
} transactioncommit()conn.is_open() == falseconnectionconn.reconnect()connectiontransactionINSERT ... RETURNINGstd::unique_ptr make_conn() {
return std::make_unique("host=localhost dbname=test");
} OUT