0
点赞
收藏
分享

微信扫一扫

Python 调用 PG 函数

扒皮狼 2022-07-13 阅读 65


安装 psycopg2

pip3 install psycopg2

创建函数

create or replace function func_test()
returns void
language plpgsql
as
$$
declare
begin
raise info 'hello';
end ;
$$;

select * from func_test();



create or replace function func_test2(id int)
returns int
language plpgsql
as
$$
declare
res int:=0;
begin
res:=10+id;
return res;

end ;
$$;

create or replace function func_test3(id int, out id2 int)
returns void
language plpgsql
as
$$
declare
begin
id2:=10+id;
end ;
$$;

编写Python测试代码

# -*- coding: utf-8 -*-
import psycopg2
t_dsn="host=192.168.0.205 port=5432 dbname=postgres user=postgres password=passwd"
dbconn = psycopg2.connect(t_dsn)
myCursor = dbconn.cursor()

# 无参函数
print("无参函数")
myCursor.callproc('func_test', ())
a_results = myCursor.fetchone()
print(a_results)


# 带有一个参数的函数
print("带有一个参数的函数")
myCursor.callproc('func_test2', ([1]))
a_results = myCursor.fetchone()
print(a_results)




# 带有 out 参数的函数
print("带有 out 参数的函数")
myCursor.callproc('func_test3', ([2]))
a_results = myCursor.fetchone()
print(a_results)


myCursor.close()
dbconn.close()

  • 结果

D:\>python3 test.py
无参函数
('',)
带有一个参数的函数
(11,)
带有 out 参数的函数
(12,)

D:\>


举报

相关推荐

0 条评论