从 Python 中的 cx_Oracle PL/SQL 调用返回变量 [英] Return variable from cx_Oracle PL/SQL call in Python

查看:31
本文介绍了从 Python 中的 cx_Oracle PL/SQL 调用返回变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to execute an Oracle PL/SQL statement via cx_oracle in Python. Code looks like this:

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 "
".join([str(err.code),err.message,err.context])

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

The code is running without problems, but is there any chance to get the result back to Python?

推荐答案

您可以像这样将输入和输出变量绑定到块.

You can bind input and output variables to the block like so.

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 块中对输入和输出变量使用常规绑定符号 (:)
  2. 对于输出变量,从游标(适当类型)中获取一个变量
  3. 在执行调用中,为输入变量和 (2) 中的变量提供值作为参数
  4. 从输出变量中检索值

脚本应该打印

Average of 23 and 55 is: 39.0

这篇关于从 Python 中的 cx_Oracle PL/SQL 调用返回变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆