python讀取oracle函數(shù)返回值
在oracle中創(chuàng)建一個函數(shù),本來是想返回一個index table的,沒有成功。想到文本也可以傳輸信息,就突然來了靈感,把返回值設(shè)置文本格式。
考慮到返回數(shù)據(jù)量可能會很大,varchar2類型長度吃緊,于是將返回值類型設(shè)置為clob。
我是用scott用戶的測試表emp,這個是函數(shù)定義情況:
create or replace function test_query_func(dept varchar2) return clob is type test_record is record (rec_empno emp.empno%type, rec_ename emp.ename%type, rec_job emp.job%type, rec_sal emp.sal%type); type test_query_arr is table of test_record index by binary_integer; cursor cur is select empno, ename, job, sal from emp where deptno = dept; test_query test_query_arr; i integer := 0; ss varchar2(200) := ''; res clob := '['; begin for c in cur loop i := i + 1; test_query(i) := c; end loop; for q in 1..test_query.count loop ss := '(''' || test_query(q).rec_empno || ''', ''' || test_query(q).rec_ename || ''', ''' || test_query(q).rec_job || ''', ''' || test_query(q).rec_sal || ''')'; if q < test_query.count then ss := ss || ','; end if; res := res || ss; end loop; res := res || ']'; return res; end;
可以在pl/sql developer測試這個函數(shù)的返回值:
begin dbms_output.put_line(test_query_func('30')); end;
輸出結(jié)果:
[('7499', 'ALLEN', 'SALESMAN', '1600'),('7521', 'WARD', 'SALESMAN', '1250'),('7654', 'MARTIN', 'SALESMAN', '1250'),('7698', 'BLAKE', 'MANAGER', '2850'),('7844', 'TURNER', 'SALESMAN', '1500'),('7900', 'JAMES', 'CLERK', '950')]
其實已經(jīng)定義成一個python中列表中包含元組子元素的樣式。
下面是python中的代碼,用python連接oracle需要cx_Oracle庫:
import cx_Oracle as ora; con = ora.connect('scott/scott@oradb'); cur = con.cursor(); cur.execute('select test_query_func(30) from dual'); res = cur.fetchall()[0][0].read(); cur.close(); con.close(); data = eval(res); import pandas as pd; df = pd.DataFrame(data, columns = ['empno', 'ename', 'job', 'sal']); print(df)
這樣oracle中函數(shù)返回的長字符串值就轉(zhuǎn)化為DataFrame對象了:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pycharm命令終端運行python文件以及傳遞參數(shù)方式
這篇文章主要介紹了pycharm命令終端運行python文件以及傳遞參數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06Python中文分詞實現(xiàn)方法(安裝pymmseg)
這篇文章主要介紹了Python中文分詞實現(xiàn)方法,通過安裝pymmseg來實現(xiàn)分詞功能,涉及pymmseg的下載、解壓、安裝及使用技巧,需要的朋友可以參考下2016-06-06python元組和字典的內(nèi)建函數(shù)實例詳解
這篇文章主要介紹了python元組和字典的內(nèi)建函數(shù),結(jié)合實例形式詳細(xì)分析了Python元組和字典的各種常見內(nèi)建函數(shù)功能與相關(guān)使用技巧,需要的朋友可以參考下2019-10-10解決Pycharm 中遇到Unresolved reference ''sklearn''的問題
這篇文章主要介紹了解決Pycharm 中遇到Unresolved reference 'sklearn'的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07python模塊與C和C++動態(tài)庫相互調(diào)用實現(xiàn)過程示例
這篇文章主要為大家介紹了python模塊與C和C++動態(tài)庫之間相互調(diào)用的實現(xiàn)過程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11