PostgreSQL - C/C++ 接口


本教程将使用libpqxx库,它是 PostgreSQL 的官方 C++ 客户端 API。libpqxx 的源代码在 BSD 许可证下可用,因此您可以自由下载它、将其传递给其他人、更改它、出售它、将其包含在您自己的代码中,以及与您选择的任何人共享您的更改。

安装

最新版本的 libpqxx 可以从链接Download Libpqxx下载。因此,下载最新版本并按照以下步骤操作 -

wget http://pqxx.org/download/software/libpqxx/libpqxx-4.0.tar.gz
tar xvfz libpqxx-4.0.tar.gz
cd libpqxx-4.0
./configure
make
make install

在开始使用 C/C++ PostgreSQL 界面之前,请在 PostgreSQL 安装目录中找到pg_hba.conf文件并添加以下行 -

# IPv4 local connections:
host    all         all         127.0.0.1/32          md5

如果 postgres 服务器没有运行,您可以使用以下命令启动/重新启动它 -

[root@host]# service postgresql restart
Stopping postgresql service:                               [  OK  ]
Starting postgresql service:                               [  OK  ]

C/C++ 接口 API

以下是重要的接口例程,可以满足您从 C/C++ 程序使用 PostgreSQL 数据库的要求。如果您正在寻找更复杂的应用程序,那么您可以查看 libpqxx 官方文档,或者您可以使用商业可用的 API。

S. 编号 接口及说明
1

pqxx::连接 C( const std::string & dbstring )

这是一个将用于连接到数据库的 typedef。这里, dbstring 提供连接数据库所需的参数,例如dbname = testdb user = postgres password=pass123 hostaddr=127.0.0.1 port=5432

如果连接成功建立,那么它会创建带有连接对象的C,该对象提供各种有用的公共函数。

2

C.is_open()

is_open() 方法是连接对象的公共方法,返回布尔值。如果连接处于活动状态,则此方法返回 true,否则返回 false。

3

C.断开连接()

该方法用于断开已打开的数据库连接。

4

pqxx::工作 W( C )

这是一个 typedef,将用于使用连接 C 创建事务对象,最终将用于在事务模式下执行 SQL 语句。

如果事务对象创建成功,则将其分配给变量 W,该变量将用于访问与事务对象相关的公共方法。

5

W.exec(const std::string & sql)

事务对象的这个公共方法将用于执行 SQL 语句。

6

W.commit()

事务对象的这个公共方法将用于提交事务。

7

W.abort()

事务对象的这个公共方法将用于回滚事务。

8

pqxx::非事务 N( C )

这是一个 typedef,它将用于使用连接 C 创建一个非事务对象,最终将用于在非事务模式下执行 SQL 语句。

如果事务对象创建成功,则将其分配给变量 N,该变量将用于访问与非事务对象相关的公共方法。

9

N.exec(const std::string & sql)

非事务对象的这个公共方法将用于执行 SQL 语句并返回一个结果对象,该结果对象实际上是一个保存所有返回记录的迭代器。

连接到数据库

以下 C 代码段显示了如何连接到在端口 5432 上的本地计算机上运行的现有数据库。这里,我使用反斜杠 \ 来继续行。

#include <iostream>
#include <pqxx/pqxx> 

using namespace std;
using namespace pqxx;

int main(int argc, char* argv[]) {
   try {
      connection C("dbname = testdb user = postgres password = cohondob \
      hostaddr = 127.0.0.1 port = 5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }
      C.disconnect ();
   } catch (const std::exception &e) {
      cerr << e.what() << std::endl;
      return 1;
   }
}

现在,让我们编译并运行上述程序以连接到我们的数据库testdb ,该数据库已在您的架构中可用,并且可以使用用户postgres和密码pass123进行访问。

您可以根据数据库设置使用用户 ID 和密码。请记住按给定的顺序保留 -lpqxx 和 -lpq!否则,链接器将强烈抱怨缺少名称以“PQ”开头的函数。

$g++ test.cpp -lpqxx -lpq
$./a.out
Opened database successfully: testdb

创建一个表

以下 C 代码段将用于在先前创建的数据库中创建一个表 -

#include <iostream>
#include <pqxx/pqxx> 

using namespace std;
using namespace pqxx;

int main(int argc, char* argv[]) {
   char * sql;
   
   try {
      connection C("dbname = testdb user = postgres password = cohondob \
      hostaddr = 127.0.0.1 port = 5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }

      /* Create SQL statement */
      sql = "CREATE TABLE COMPANY("  \
      "ID INT PRIMARY KEY     NOT NULL," \
      "NAME           TEXT    NOT NULL," \
      "AGE            INT     NOT NULL," \
      "ADDRESS        CHAR(50)," \
      "SALARY         REAL );";

      /* Create a transactional object. */
      work W(C);
      
      /* Execute SQL query */
      W.exec( sql );
      W.commit();
      cout << "Table created successfully" << endl;
      C.disconnect ();
   } catch (const std::exception &e) {
      cerr << e.what() << std::endl;
      return 1;
   }

   return 0;
}

当编译并执行上面给定的程序时,它将在 testdb 数据库中创建 COMPANY 表并显示以下语句 -

Opened database successfully: testdb
Table created successfully

插入操作

以下 C 代码段显示了如何在上面示例中创建的 COMPANY 表中创建记录 -

#include <iostream>
#include <pqxx/pqxx> 

using namespace std;
using namespace pqxx;

int main(int argc, char* argv[]) {
   char * sql;
   
   try {
      connection C("dbname = testdb user = postgres password = cohondob \
      hostaddr = 127.0.0.1 port = 5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }

      /* Create SQL statement */
      sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "  \
         "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \
         "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "  \
         "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); "     \
         "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
         "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \
         "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
         "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";

      /* Create a transactional object. */
      work W(C);
      
      /* Execute SQL query */
      W.exec( sql );
      W.commit();
      cout << "Records created successfully" << endl;
      C.disconnect ();
   } catch (const std::exception &e) {
      cerr << e.what() << std::endl;
      return 1;
   }

   return 0;
}

当上面给定的程序被编译并执行时,它将在 COMPANY 表中创建给定的记录,并显示以下两行 -

Opened database successfully: testdb
Records created successfully

选择操作

以下 C 代码段显示了如何从上面示例中创建的 COMPANY 表中获取和显示记录 -

#include <iostream>
#include <pqxx/pqxx> 

using namespace std;
using namespace pqxx;

int main(int argc, char* argv[]) {
   char * sql;
   
   try {
      connection C("dbname = testdb user = postgres password = cohondob \
      hostaddr = 127.0.0.1 port = 5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }

      /* Create SQL statement */
      sql = "SELECT * from COMPANY";

      /* Create a non-transactional object. */
      nontransaction N(C);
      
      /* Execute SQL query */
      result R( N.exec( sql ));
      
      /* List down all the records */
      for (result::const_iterator c = R.begin(); c != R.end(); ++c) {
         cout << "ID = " << c[0].as<int>() << endl;
         cout << "Name = " << c[1].as<string>() << endl;
         cout << "Age = " << c[2].as<int>() << endl;
         cout << "Address = " << c[3].as<string>() << endl;
         cout << "Salary = " << c[4].as<float>() << endl;
      }
      cout << "Operation done successfully" << endl;
      C.disconnect ();
   } catch (const std::exception &e) {
      cerr << e.what() << std::endl;
      return 1;
   }

   return 0;
}

当上面给定的程序被编译并执行时,它将产生以下结果 -

Opened database successfully: testdb
ID = 1
Name = Paul
Age = 32
Address = California
Salary = 20000
ID = 2
Name = Allen
Age = 25
Address = Texas
Salary = 15000
ID = 3
Name = Teddy
Age = 23
Address = Norway
Salary = 20000
ID = 4
Name = Mark
Age = 25
Address = Rich-Mond
Salary = 65000
Operation done successfully

更新操作

以下 C 代码段显示了如何使用 UPDATE 语句更新任何记录,然后从 COMPANY 表中获取并显示更新的记录 -

#include <iostream>
#include <pqxx/pqxx> 

using namespace std;
using namespace pqxx;

int main(int argc, char* argv[]) {
   char * sql;
   
   try {
      connection C("dbname = testdb user = postgres password = cohondob \
      hostaddr = 127.0.0.1 port = 5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }
      
      /* Create a transactional object. */
      work W(C);
      /* Create  SQL UPDATE statement */
      sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1";
      /* Execute SQL query */
      W.exec( sql );
      W.commit();
      cout << "Records updated successfully" << endl;
      
      /* Create SQL SELECT statement */
      sql = "SELECT * from COMPANY";

      /* Create a non-transactional object. */
      nontransaction N(C);
      
      /* Execute SQL query */
      result R( N.exec( sql ));
      
      /* List down all the records */
      for (result::const_iterator c = R.begin(); c != R.end(); ++c) {
         cout << "ID = " << c[0].as<int>() << endl;
         cout << "Name = " << c[1].as<string>() << endl;
         cout << "Age = " << c[2].as<int>() << endl;
         cout << "Address = " << c[3].as<string>() << endl;
         cout << "Salary = " << c[4].as<float>() << endl;
      }
      cout << "Operation done successfully" << endl;
      C.disconnect ();
   } catch (const std::exception &e) {
      cerr << e.what() << std::endl;
      return 1;
   }

   return 0;
}

当上面给定的程序被编译并执行时,它将产生以下结果 -

Opened database successfully: testdb
Records updated successfully
ID = 2
Name = Allen
Age = 25
Address = Texas
Salary = 15000
ID = 3
Name = Teddy
Age = 23
Address = Norway
Salary = 20000
ID = 4
Name = Mark
Age = 25
Address = Rich-Mond
Salary = 65000
ID = 1
Name = Paul
Age = 32
Address = California
Salary = 25000
Operation done successfully

删除操作

以下 C 代码段显示了如何使用 DELETE 语句删除任何记录,然后从 COMPANY 表中获取并显示剩余记录 -

#include <iostream>
#include <pqxx/pqxx> 

using namespace std;
using namespace pqxx;

int main(int argc, char* argv[]) {
   char * sql;
   
   try {
      connection C("dbname = testdb user = postgres password = cohondob \
      hostaddr = 127.0.0.1 port = 5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }
      
      /* Create a transactional object. */
      work W(C);
      /* Create  SQL DELETE statement */
      sql = "DELETE from COMPANY where ID = 2";
      /* Execute SQL query */
      W.exec( sql );
      W.commit();
      cout << "Records deleted successfully" << endl;
      
      /* Create SQL SELECT statement */
      sql = "SELECT * from COMPANY";

      /* Create a non-transactional object. */
      nontransaction N(C);
      
      /* Execute SQL query */
      result R( N.exec( sql ));
      
      /* List down all the records */
      for (result::const_iterator c = R.begin(); c != R.end(); ++c) {
         cout << "ID = " << c[0].as<int>() << endl;
         cout << "Name = " << c[1].as<string>() << endl;
         cout << "Age = " << c[2].as<int>() << endl;
         cout << "Address = " << c[3].as<string>() << endl;
         cout << "Salary = " << c[4].as<float>() << endl;
      }
      cout << "Operation done successfully" << endl;
      C.disconnect ();
   } catch (const std::exception &e) {
      cerr << e.what() << std::endl;
      return 1;
   }

   return 0;
}

当上面给定的程序被编译并执行时,它将产生以下结果 -

Opened database successfully: testdb
Records deleted successfully
ID = 3
Name = Teddy
Age = 23
Address = Norway
Salary = 20000
ID = 4
Name = Mark
Age = 25
Address = Rich-Mond
Salary = 65000
ID = 1
Name = Paul
Age = 32
Address = California
Salary = 25000
Operation done successfully