首頁  >  文章  >  後端開發  >  python讀取oracle函數回傳值

python讀取oracle函數回傳值

WBOY
WBOY原創
2016-08-04 08:55:411522瀏覽

在oracle中建立一個函數,本來是想要回傳一個index table的,沒有成功。想到文字也可以傳遞訊息,就突然來了靈感,把返回值設定文字格式。
考慮到回傳資料量可能會很大,varchar2類型長度吃緊,於是將回傳值類型設為clob。 
我是用scott用戶的測試表emp,這個是函數定義狀況:

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測試這個函數的回傳值:

 begin
 dbms_output.put_line(test_query_func('30'));
 end; 

輸出結果:
[('7499', 'ALLEN', 'SALESMAN', '1600'),('7521', 'WARD', 'SALESMAN', '1250'),('7654', 'MARTIN', 'SALESMAN' , '1250'),('7698', 'BLAKE', 'MANAGER', '2850'),('7844', 'TURNER', 'SALESMAN', '1500'),('7900', 'JAMES' , 'CLERK', '950')]
 其實已經定義成一個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中函數回傳的長字串值就轉換成DataFrame物件了:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn