- 论坛徽章:
- 0
|
/*
* PostgreSQL 是一种非常复杂的对象-关系型数据库管理系统(ORDBMS),
* 也是目前功能最强大,特性最丰富和最复杂的自由软件数据库系统。
* 有些特性甚至连商业数据库都不具备。
*
* 这个起源于伯克利(BSD)的数据库研究计划目前已经衍生成一项国际开发项目, 并且有非常广泛的用户。
* 但是在国内知道的人却不多前些日子看到了postgres中文网站的主要人员何伟平
* 用了4年时间进行文档的汉化工作深受感动,于是觉得我们一直在研究postgres系统,是不是也应该
* 为postgres在中国的普及做点工作。
*
* 以后我会陆续在chinaunix的postgres论坛刊登文章的。
*
* 该程序在postgres7.3下编译运行通过(你需要指定libpq.a的路径)
* 编译方法:gcc -o <执行程序名>; <源文件(该程序)>; -lcrypt libpq.a
*/
#include <stdio.h>;
#include <stdlib.h>;
#include "../include/libpq-fe.h"
static void
safe_exit(PGconn *conn)
{
PQfinish(conn);
exit(1);
}
int main(void)
{
char *pghost,
*pgport,
*pgoptions,
*pgtty;
char *dbName;
int nFields;
int i, j;
PGconn *conn;
PGresult *res;
/*
* 设置连接参数
*/
pghost = NULL; /* 主机名或者IP地址 NULL则是本地连接 */
pgport = NULL; /* 端口号 NULL则是缺省端口5432 */
pgoptions = NULL; /* 一些特殊的选项不过看代码没什么用NULL即可 */
pgtty = NULL; /* 用于调试所用后端知道是谁在连接 */
dbName = "postgres"; /* 要连接的数据库 */
/* 开始连接到数据库 */
conn = PQsetdb(pghost, pgport, pgoptions, pgtty, dbName);
/* 检查是否连接到了postgres后端进程 */
if (PQstatus(conn) == CONNECTION_BAD)
{
fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
/* 获得错误消息 */
fprintf(stderr, "%s", PQerrorMessage(conn));
safe_exit(conn);
}
/* 执行begin查询开始一个事务 */
res = PQexec(conn, "BEGIN" ;
/* 检查返回状态 */
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "BEGIN command failed\n" ;
/* 清空结果 */
PQclear(res);
safe_exit(conn);
}
/*
* 为了避免内存耗尽,应该clear结果当不再需要的时候
*/
PQclear(res);
/*
* 声明一个光标为查询系统表pg_database(保存数据库信息)
* postgres不像SQLserver,必须先声明个光标
*/
res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database" ;
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "DECLARE CURSOR command failed\n" ;
PQclear(res);
safe_exit(conn);
}
PQclear(res);
/*
* 从光标中fetch结果
*/
res = PQexec(conn, "FETCH ALL in myportal" ;
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
fprintf(stderr, "FETCH ALL command didn't return tuples properly\n" ;
PQclear(res);
safe_exit(conn);
}
/* 获得字段名字并打印 */
nFields = PQnfields(res);
for (i = 0; i < nFields; i++)
printf("%-15s", PQfname(res, i));
printf("\n\n" ;
/* 获得记录并打印,在postgres代码中tuple(元组)就是记录 */
for (i = 0; i < PQntuples(res); i++)
{
for (j = 0; j < nFields; j++)
printf("%-15s", PQgetvalue(res, i, j));
printf("\n" ;
}
PQclear(res);
/* 关闭光标 */
res = PQexec(conn, "CLOSE myportal" ;
PQclear(res);
/* 结束事务 */
res = PQexec(conn, "END" ;
PQclear(res);
/* 断开连接 */
PQfinish(conn);
return 0;
} |
|