PGresult *res = PQexec(conn, "BEGIN");
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
PQclear(res);
// handle error
}
PQclear(res);
PGresult *res = PQexec(conn, "COMMIT");
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "COMMIT command failed: %s", PQerrorMessage(conn));
PQclear(res);
// handle error
}
PQclear(res);
PGresult *res = PQexec(conn, "ROLLBACK");
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "ROLLBACK command failed: %s", PQerrorMessage(conn));
PQclear(res);
// handle error
}
PQclear(res);
PGresult *res = PQexec(conn, "SELECT current_transaction()");
if (PQresultStatus(res) == PGRES_TUPLES_OK) {
int currentTx = atoi(PQgetvalue(res, 0, 0));
printf("Current transaction: %d\n", currentTx);
} else {
fprintf(stderr, "Error retrieving current transaction: %s", PQerrorMessage(conn));
}
PQclear(res);
try {
// perform operations within transaction
} catch (std::exception& e) {
// handle exception
PGresult *res = PQexec(conn, "ROLLBACK");
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "ROLLBACK command failed: %s", PQerrorMessage(conn));
}
PQclear(res);
}
通过上述技巧,可以在C++程序中有效地处理PostgreSQL数据库的事务。