python - 从 Python 中的 cx_Oracle PL/SQL 调用返回变量

标签 python plsql cx-oracle

我想在 Python 中通过 cx_oracle 执行 Oracle PL/SQL 语句。代码如下所示:

db = cx_Oracle.connect(user, pass, dsn_tns)
cursor = db.cursor()

... 

sel = """
DECLARE
  c   NUMBER := 0.2;
  mn  NUMBER := 1.5;
  res NUMBER;
BEGIN
  res := c+mn/6.;
END;
"""
try:
  cursor.execute(sel) 
  print "PL/SQL successful executed ..."
except cx_Oracle.DatabaseError as e:
  err, = e.args
  print "\n".join([str(err.code),err.message,err.context])

代码运行没有问题,但是否有机会将结果返回给 Python?

最佳答案

您可以像这样将输入和输出变量绑定(bind)到 block 。

import cx_Oracle

SQL_BLOCK = '''
DECLARE
  v_first   NUMBER;
  v_second  NUMBER;
  v_result  NUMBER;
BEGIN
  v_first  := :i_first;   -- (1)
  v_second := :i_second;  -- (1)

  v_result := (v_first + v_second) / 2;

  :o_result := v_result;  -- (1)
END;
'''

with cx_Oracle.connect('hr/hr@xe') as db:
    cur = db.cursor()
    o_result = cur.var(cx_Oracle.NUMBER) # (2)
    cur.execute(SQL_BLOCK, i_first=23, i_second=55, o_result=o_result) # (3)
    res = o_result.getvalue()  # (4)
    print('Average of 23 and 55 is: {}'.format(res))
  1. 在 PL/SQL block 中对输入和输出变量使用常规绑定(bind)符号 (:)
  2. 对于输出变量,从游标获取一个变量(适当的类型)
  3. 在执行调用中,为输入变量和 (2) 中的变量提供值作为参数
  4. 从输出变量中检索值

脚本应该打印

Average of 23 and 55 is: 39.0

关于python - 从 Python 中的 cx_Oracle PL/SQL 调用返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18267935/

相关文章:

python - cx_Oracle.InterfaceError : Unable to acquire Oracle environment handle in linux

sql - 从oracle中的另一个模式中选择数据

c++ - 使用 C++ 或 Python 生成随机数

sql - 长期使用 Oracle 的用户切换到 MySQL,有什么需要注意的问题吗?

plsql - Oracle 包规范何时变为无效

plsql - 将 PL/SQL 转换为 Hive QL

python - TemplateView 的 post() 到 get_context_data() 方法的变量

python - Tkinter 按钮不运行命令

python - 如何使用 matplotlib 与极坐标图共享轴

python - cx_Oracle.InterfaceError : Unable to acquire Oracle environment handle Mac