前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >原 PostgreSQL用C完成存储过程例子

原 PostgreSQL用C完成存储过程例子

作者头像
王果壳
发布2018-05-17 11:54:38
1.1K0
发布2018-05-17 11:54:38
举报
文章被收录于专栏:王硕

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

准备工作

1、安装数据库

2、建立表test

代码语言:javascript
复制
highgo=# create table test(id int, name text, label int);
CREATE TABLE

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

代码语言:javascript
复制
#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编译

代码语言:javascript
复制
gcc -fpic -I/opt/HighGo/db/20150401/include/postgresql/server/ -shared -o myapi.so myapi.c

5、复制到lib目录下

代码语言:javascript
复制
cp myapi.so /opt/HighGo/db/20150401/lib/postgresql/

6、加载到服务器

代码语言:javascript
复制
highgo=# load 'myapi';
LOAD

7、建立函数

代码语言:javascript
复制
highgo=# create function mydele(integer) returns integer as '$libdir/myapi.so','mydelete' language c strict;
CREATE FUNCTION
highgo=#

8、效果

代码语言:javascript
复制
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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档