1. 程式人生 > >在Python中使用cx_Oracle呼叫Oracle儲存過程

在Python中使用cx_Oracle呼叫Oracle儲存過程

本文測試在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_Oracle 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, NVARCHAR2, LONG cx_Oracle.STRING str
CHAR cx_Oracle.FIXED_CHAR str
NUMBER cx_Oracle.NUMBER int
FLOAT cx_Oracle.NUMBER float
DATE cx_Oracle.DATETIME datetime.datetime
TIMESTAMP cx_Oracle.TIMESTAMP datetime.datetime
CLOB cx_Oracle.CLOB cx_Oracle.LOB
BLOB cx_Oracle.BLOB cx_Oracle.LOB