本文测试在Python中通过cx_Oracle调用PL/SQL。
首先,在数据库端创建简单的存储过程。
create or replace procedure test_msg(i_user in varchar2, o_msg out varchar2) is
begin
o_msg := i_user ||', Good Morning!';
end;
然后,开始在Python命令行中进行存储过程调用。
import cx_Orace as cx
conn = cx.connect('database connecting string')
cursor = conn.cursor()
#声明变量
user = 'Nick' #plsql入参
msg = cursor.var(cx_Oracle.STRING) #plsql出参
#调用存储过程
cursor.callproc('test_msg', [user, msg]) #['Nick', 'Nick, Good Morning!']
#打印返回值
print msg #<cx_Oracle.STRING with value 'Nick, Good Morning!'>
print msg.getvalue() #Nick, Good Morning!
#资源关闭
cursor.close()
conn.close()
延伸阅读:
存储过程、cx_Oracle、Python的对象类型之间存在转换关系。具体如下:
Oracle | cx_Oracle | Python |
VARCHAR2 | cx_Oracle.STRING | str |
CHAR | cx_Oracle.FIXED_CHAR | |
NUMBER | cx_Oracle.NUMBER | int |
FLOAT | float | |
DATE | cx_Oracle.DATETIME | datetime.datetime |
TIMESTAMP | cx_Oracle.TIMESTAMP | |
CLOB | cx_Oracle.CLOB | cx_Oracle.LOB |
BLOB | cx_Oracle.BLOB |
转载于:https://blog.51cto.com/pierre/1623820