1.C操作postgreSql
程序:
/*程序在redhat6.0上调试通过
*该程序使用pgsql的内部函数实现数据库的一般功能
*这里create,insert,select,update,drop几个最常用的SQL语句
*具体还有些更强大的功能,如阻塞等,需要进一步研究
*详细资料可以查看参考手册,那边有所有的函数调用*/
/*头文件*/
#include
#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'");






