Linux中国 Linux中国门户站!
设为主页 设为主页
收藏本站 收藏本站
 
当前位置 :首页 ->Linux技术 ->系统管理 ->正文

在C下操作PostgreSql

来源:Linux-cn.com 作者:Webmaster 时间:2007-05-05 点击: [收藏] [投稿]

在C下操作PostgreSql

  前一阵子开始,我开始使用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); 

} 



 如果您对本文有任何疑问或者建议,请到讨论区发表您的意见: >> 论坛入口 <<



上一篇:客观公正地评价MySQL和PostgreSQL的优劣   下一篇:将你的网站从MySQL改为PostgreSQL(上)

文章评论】 【收藏本文】 【推荐好友】 【打印本文】 【我要投稿】 【论坛讨论
更多相关文章
Power by linux-cn.com 粤ICP备05006655号