PostgreSQL用C完成存储过程例子

前端之家收集整理的这篇文章主要介绍了PostgreSQL用C完成存储过程例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

准备工作

1、安装数据库

2、建立表test

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

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

  1. #include "postgres.h"
  2. #include "executor/spi.h"
  3. #include "utils/builtins.h"
  4.  
  5. #ifdef PG_MODULE_MAGIC
  6. PG_MODULE_MAGIC;
  7. #endif
  8.  
  9. int mydelete(int key);
  10.  
  11. int
  12. mydelete(int key)
  13. {
  14. char command[128]; //视命令长短建立相应大小的数组
  15. int ret;
  16. int proc; //对表数据操作的行数
  17.  
  18. /* 将命令赋值到command */
  19. sprintf(command,"update test set label = 0 where id = %d and label = 1; ",key);
  20.  
  21. SPI_connect(); //内部链接
  22. ret = SPI_exec( command,0); //执行操作
  23. proc = SPI_processed; //为行数赋值
  24. SPI_finish(); //中断连接
  25. return (proc); //将操作行数作为返回结果
  26. }

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

编译到安装

4、gcc编译

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

5、复制到lib目录下

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

6、加载到服务器

  1. highgo=# load 'myapi';
  2. LOAD

7、建立函数

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

8、效果

  1. highgo=# insert into test values (1,'jim',1);
  2. INSERT 0 1
  3. highgo=# insert into test values (2,'tom',1);
  4. INSERT 0 1
  5. highgo=# select * from test;
  6. id | name | label
  7. ----+------+-------
  8. 1 | jim | 1
  9. 2 | tom | 1
  10.  
  11. highgo=# select mydele(1);
  12. mydele
  13. --------
  14. 1
  15. (1 row)
  16. highgo=# select * from test;
  17. id | name | label
  18. ----+------+-------
  19. 2 | tom | 1
  20. 1 | jim | 0

猜你在找的Postgre SQL相关文章