如何使用 Python 读取 Oracle 存储过程的内容

How to i read the contents of Oracle stored procedures using Python

我正在尝试使用 python 读取存储过程的 contents/code。

我使用了cx_Oracle函数来建立与oracle数据库的连接。

这是代码

import cx_Oracle as co
import pandas as pd

dsn_tsn = co.makedsn(ip,port,SID)
db=co.connect(username,password,dsn_tsn)
cursor = db.cursor()

cursor.callproc(procedure_name,['argument']) # will be me result of the procedure.

但是,我正在尝试阅读程序本身的代码。有什么功能可以做到这一点吗?

可以通过user_source视图访问存储过程代码。所以,如果你查询它,你会看到你想要的。方法如下:

SQL> create or replace procedure p_test is
  2  begin
  3    null;
  4  end;
  5  /

Procedure created.

SQL> desc user_source
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 NAME                                               VARCHAR2(30)
 TYPE                                               VARCHAR2(12)
 LINE                                               NUMBER
 TEXT                                               VARCHAR2(4000)

SQL> select text from user_source where name = 'P_TEST' and type = 'PROCEDURE';

TEXT
--------------------------------------------------------------------------------
procedure p_test is
begin
  null;
end;

SQL>

不过,由于我不会说话 Python,因此我无法提供您需要在那里使用的实际代码。我写的最后一个select就是你需要的;我希望你能设法使用它。祝你好运!

您可以通过这种方式从您的代码中调用 DBMS_METADATA.GET_DDL 函数

import cx_Oracle

db = cx_Oracle.connect("<uname>/<pwd>@<host>:<port>/<service_name>")
cursor = db.cursor()


    def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
        if defaultType == cx_Oracle.CLOB:
            return cursor.var(cx_Oracle.LONG_STRING, arraysize = cursor.arraysize)

    cursor.outputtypehandler = OutputTypeHandler
    cursor.execute("SELECT DBMS_METADATA.GET_DDL('PROCEDURE', :PrcName) FROM DUAL",
            PrcName="MY_LITTLE_PROC")

    print("returned DDL is :",cursor.fetchall())