在C下操作PostgreSql

王朝mssql·作者佚名  2008-05-18
窄屏简体版  字體: |||超大  

在C下操作PostgreSql

LinuxAid.com.cn 01-09-06 12:29 779p eight

在C下操作PostgreSql

作者 EIGHT

前一阵子开始,我开始使用postgresql,把最近写的一个简单的程序拿出来与

大家交流交流,我也是初学者,请多多指教. Postgresql用rpm包安装极为简单,很

容易就成功.改天我写一写安装过程. 但我用tar包安装没有成功,安装过程都参

照参考手册上所写的,就是不行,哪位有安装成功过,把安装过程写下来吧. 总的

感觉是postgresql是个好东东,简单易学,功能方面也不差.下面这个程序涉及的

函数与功能虽然不多,却是操作postgresql 最经常用到的.

程序:

/*程序在redhat6.0上调试通过

*该程序使用pgsql的内部函数实现数据库的一般功能

*这里create,insert,select,update,drop几个最常用的SQL语句

*具体还有些更强大的功能,如阻塞等,需要进一步研究

*详细资料可以查看参考手册,那边有所有的函数调用*/

/*头文件*/

#include <stdio.h>

#include

main() {

char *pghost,

*pgport,

*pgoptions,

*pgtty;

char *dbName;

int nFields;

int i, j;

PGconn *conn;

PGresult *res;

/*

* 程序开头需要设定连接到数据库服务器的一些参数,如果设置值为

NULL,

* 则使用环境变量中设置的缺省值。

*/

pghost = NULL; /* 服务器的主机名 */

pgport = NULL; /* 服务器端口 */

pgoptions = NULL;/* 附加的功能参数 */

pgtty = NULL; /* 服务器的调试tty */

dbName = "mytest"; /* 要操作的数据库名 */

/* 连接数据库服务器*/

conn = PQsetdb(pghost, pgport, pgoptions, pgtty, dbName);

/* 检查连接是否成功 */

if (PQstatus(conn) == CONNECTION_BAD)

{

fprintf(stderr, "Connection to database '%s' failed.

", dbName);

fprintf(stderr, "%s", PQerrorMessage(conn));

exit_nicely(conn);

}

/* 开始处理数据块 */

res = PQexec(conn, "BEGIN");

if (!res' 'PQresultStatus(res) != PGRES_COMMAND_OK)

{

fprintf(stderr, "BEGIN command failed

");

PQclear(res);

exit_nicely(conn);

}

/*调用PQclear在PQresult的游标不再使用后清除游标,防止内存溢出 */

PQclear(res);

/* 建立一个叫test1的表 */

PQexec(conn,"create table test1 (name char(20),age int4)");

/* 插入数据 */

PQexec(conn,"insert into test1 values ('cjm',10)");

PQexec(conn,"insert into test1 values ('eight',20)");

PQexec(conn,"insert into test1 values ('linuxaid',30)");

/* 开始查询 */

printf("all the date is:

");

res = PQexec(conn, "select * from test1");

for (i = 0; i < PQntuples(res); i++)

{

for (j = 0; j < PQnfields(res); j++)

printf("%-15s", PQgetvalue(res, i, j));

printf("

");

}

PQclear(res);

/* 使用SQL的update函数 */

PQexec(conn,"update test1 set age=25 where name='eight'");

/* 打印出更新后的数据 */

printf("

the new date is:

");

res = PQexec(conn, "select * from test1");

for (i = 0; i < PQntuples(res); i++)

{

for (j = 0; j < PQnfields(res); j++)

printf("%-15s", PQgetvalue(res, i, j));

printf("

");

}

PQclear(res);

/* 删除表 */

PQexec(conn,"drop table test1");

/* 关闭和数据库的连接 */

PQfinish(conn);

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航