PostgreSQL 的 C 编程接口

好风 创建于 2011-11-01 14:35
查看 442 次, 2011-11-02 18:20好风 更新
源代码(Markup) 下载

安装

Debian :

1
# aptitude install libpq-dev

Fedora :

1
# yum install postgresql-devel

示例

执行简单 SQL 语句

参考: Accessing PostgreSQL in C/C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdio.h>
#include <stdlib.h>
#include <postgresql/libpq-fe.h>
#include <string.h>

int main(int argc, char *argv[]) {

     PGconn          *conn;
     PGresult        *res;
     int             rec_count;
     int             row;
     int             col;

     conn = PQconnectdb("dbname=ljdata host=localhost user=dataman password=supersecret");

     if (PQstatus(conn) == CONNECTION_BAD) {
          puts("We were unable to connect to the database");
          exit(0);
     }

     res = PQexec(conn, "update people set phonenumber=\'5055559999\' where id=3");

     res = PQexec(conn, "select lastname,firstname,phonenumber from people order by id");

     if (PQresultStatus(res) != PGRES_TUPLES_OK) {
          puts("We did not get any data!");
          exit(0);
     }

     rec_count = PQntuples(res);

     printf("We received %d records.\n", rec_count);
     puts("==========================");

     for (row=0; row<rec_count; row++) {
          for (col=0; col<3; col++) {
               printf("%s\t", PQgetvalue(res, row, col));
          }
          puts("");
     }

     puts("==========================");

     PQclear(res);
     PQfinish(conn);

     return 0;
}

将上面程序保存为 tdb.c , 编绎:

1
$ cc -Wall -g tdb.c -o tdb -lpq

FAQ

如何找到 libpq-fe.h

不同的系统可能将头文件安装在不同的地方, (如 Debian 默认安装在 /usr/include/postgresql , 而 Fedora 安装在 /usr/include). 我们在需要时, 可以用 pg_config 命令获取.

1
$ pg_config --includedir

convert SQL timestamp to unix timestamp

参考: PostgreSQL : SQL timestamp to Unix timestamp using libpq

将下面 SQL 语句灵活运用:

1
SELECT extract(epoch FROM now());

time_t to timestamp

1
select 1079497559::abstime::timestamp;