LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 2053|回复: 2

在C下操作PostgreSql

[复制链接]
发表于 2003-6-21 12:01:44 | 显示全部楼层 |阅读模式
在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);

}
发表于 2007-10-17 10:00:44 | 显示全部楼层
用上你的代码了,谢谢!
回复 支持 反对

使用道具 举报

发表于 2007-10-28 11:12:43 | 显示全部楼层
正需要用到这个
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表