Chinaunix首页 | 论坛 | 博客
  • 博客访问: 839292
  • 博文数量: 150
  • 博客积分: 5123
  • 博客等级: 大校
  • 技术积分: 1478
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-06 10:03
文章分类

全部博文(150)

文章存档

2011年(2)

2010年(139)

2009年(9)

分类:

2010-06-07 00:04:03

在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
  #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);
  }(王朝网络 wangchao.net.cn)
阅读(1017) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~