PostgreSQL C/C++接口

PostgreSQL C/C++接口

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

安装

最新版本的libpqxx可以通过以下链接下载 下载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服务器,以防它未运行:

您可以使用以下命令来启动/重新启动Postgres服务器,以防它未运行:-

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

C/C++接口API

以下是一些重要的接口例程,它们足以满足您从C/C++程序与PostgreSQL数据库交互的要求。如果您正在寻求更复杂的应用程序,您可以参考libpqxx的官方文档,或者您可以使用商业可用的API。

编号 API与说明
1 pqxx::connection 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.disconnect() 此方法用于断开已打开的数据库连接。
4 pqxx::work W( C ) 这是一个typedef,将用于使用连接C创建一个事务对象,最终将用于以事务模式执行SQL语句。 如果成功创建了事务对象,则将其分配给变量W,该变量将用于访问与事务对象相关的公共方法。
5 **W.exec(const std::string & sql) ** 这是来自事务对象的公共方法,用于执行SQL语句。
6 W.commit() 这是来自事务对象的公共方法,用于提交事务。
7 W.abort() 这是来自事务对象的公共方法,用于回滚事务。
8 pqxx::nontransaction 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

SELECT 操作

下面的 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程