手机版
你好,游客 登录 注册
背景:
阅读新闻

PostgreSQL用C完成存储过程实例

[日期:2015-11-28] 来源:oschina.net  作者:Suregogo [字体: ]

最近给客户写了一个PostgreSQL用C写的存储过程的例子,在此记录一下。

目的:用C完成一个存储过程例子,存储过程实现对表某一段进行update。

准备工作

1、安装数据库

2、建立表test

highgo=# create table test(id int, name text, label int);
CREATE TABLE

3、建立C文件,C代码如下:

#include "postgres.h"
#include "executor/spi.h"
#include "utils/builtins.h"
 
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
 
int mydelete(int key);
 
int
mydelete(int key)
{
    char command[128];  //视命令长短建立相应大小的数组
    int ret;
    int proc;                      //对表数据操作的行数
 
    /* 将命令赋值到command */
    sprintf(command, "update test set label = 0 where id = %d and label = 1; ", key);
 
    SPI_connect();            //内部链接
    ret = SPI_exec( command, 0);  //执行操作
    proc = SPI_processed;      //为行数赋值
    SPI_finish();                //中断连接
    return (proc);              //将操作行数作为返回结果
}

数据库api参考文档:http://www.postgresql.org/docs/9.4/static/spi.html

编译到安装

4、gcc编译

gcc -fpic -I/opt/HighGo/db/20150401/include/postgresql/server/ -shared -o myapi.so myapi.c

5、复制到lib目录下

cp myapi.so /opt/HighGo/db/20150401/lib/postgresql/

6、加载到服务器

highgo=# load 'myapi';
LOAD

7、建立函数

highgo=# create function mydele(integer) returns integer as '$libdir/myapi.so','mydelete' language c strict;
CREATE FUNCTION
highgo=#

8、效果

highgo=# insert into test values (1,'jim',1);
INSERT 0 1
highgo=# insert into test values (2,'tom',1);
INSERT 0 1
highgo=# select * from test;
 id | name | label
----+------+-------
  1 | jim  |    1
  2 | tom  |    1
 
highgo=# select mydele(1);
 mydele
--------
      1
(1 row)
highgo=# select * from test;
 id | name | label
----+------+-------
  2 | tom  |    1
  1 | jim  |    0

------------------------------------华丽丽的分割线------------------------------------

CentOS 6.3环境下yum安装PostgreSQL 9.3 http://www.linuxidc.com/Linux/2014-05/101787.htm

PostgreSQL缓存详述 http://www.linuxidc.com/Linux/2013-07/87778.htm

Windows平台编译 PostgreSQL http://www.linuxidc.com/Linux/2013-05/85114.htm

Ubuntu下LAPP(Linux+Apache+PostgreSQL+PHP)环境的配置与安装 http://www.linuxidc.com/Linux/2013-04/83564.htm

Ubuntu上的phppgAdmin安装及配置 http://www.linuxidc.com/Linux/2011-08/40520.htm

CentOS平台下安装PostgreSQL9.3 http://www.linuxidc.com/Linux/2014-05/101723.htm

PostgreSQL配置Streaming Replication集群 http://www.linuxidc.com/Linux/2014-05/101724.htm

如何在CentOS 7/6.5/6.4 下安装PostgreSQL 9.3 与 phpPgAdmin  http://www.linuxidc.com/Linux/2014-12/110108.htm

------------------------------------华丽丽的分割线------------------------------------

PostgreSQL 的详细介绍请点这里
PostgreSQL 的下载地址请点这里

本文永久更新链接地址http://www.linuxidc.com/Linux/2015-11/125623.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款