环境:windows10 vs2022
引入pqxxs
一些增删改查的示例代码
#include "pqxx/pqxx"
void insertPg()
{
try {
// 建立连接
pqxx::connection conn("dbname=postgres user=postgres password=123 hostaddr=127.0.0.1 port=5432");
// 添加数据
pqxx::work txn(conn);
int id = 1;
txn.exec("INSERT INTO abc (id) VALUES (" + std::to_string(id) + ")");
txn.commit();
// 关闭连接
conn.disconnect();
}
catch (const std::exception &e) {
ACOUT(e.what());
}
}
void deletepg()
{
try {
// 建立连接
pqxx::connection conn("dbname=postgres user=postgres password=123 hostaddr=127.0.0.1 port=5432");
// 删除记录
pqxx::work txn(conn);
pqxx::result res = txn.exec("DELETE FROM abc WHERE id = 1");
int num_deleted = res.affected_rows();
txn.commit();
std::stringstream ss;
ss << "删除个数: " << num_deleted;
std::string str = ss.str();
AcOUT(str.c_str());
// 关闭连接
conn.disconnect();
}
catch (const std::exception &e) {
AcOUT(e.what());
}
}
void updatePg()
{
try {
// 建立连接
pqxx::connection conn("dbname=postgres user=postgres password=123 hostaddr=127.0.0.1 port=5432");
// 更新记录
pqxx::work txn(conn);
pqxx::result res = txn.exec("UPDATE abc SET id = '789654' WHERE id = 12 RETURNING *");
txn.commit();
// 输出更新的记录信息
for (auto row : res) {
std::stringstream ss;
// ss << "id: " << row[0].as<int>() << ", name: " << row[1].as<std::string>();
ss << "id: " << row[0].as<int>();
std::string str = ss.str();
AcOUT(str.c_str());
}
// 关闭连接
conn.disconnect();
}
catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
}
添加,删除,修改,返回操作的个数
int cPG(std::string SQL) {
int num = 0;
try {
// 建立连接
pqxx::connection conn("dbname=timespace user=postgres password=asdadsadasdri hostaddr=localhost port=5432");
// 删除记录
pqxx::work txn(conn);
{
pqxx::result result = txn.exec("SET CLIENT_ENCODING TO 'GBK';");
}
pqxx::result res = txn.exec(SQL);
num = res.affected_rows();
txn.commit();
std::stringstream ss;
ss << "操作数据条数: " << num;
std::string str = ss.str();
ACOUT(str.c_str());
// 关闭连接
conn.disconnect();
}
catch (const std::exception &e) {
ACOUT(e.what());
}
return num;
}
标签:std,txn,postgres,ss,数据库,pqxx,C++,pg,conn
From: https://www.cnblogs.com/SpringBreath/p/17952553