用python讀取oracle函數傳回值

來源:互聯網
上載者:User

標籤:oracle   python   pl/sql   

在oracle中建立一個函數,本來是想返回一個index table的,沒有成功。想到文本也可以傳輸資訊,就突然來了靈感,把傳回值設定文字格式設定。


考慮到返回資料量可能會很大,varchar2類型長度吃緊,於是將傳回值類型設定為clob。


我是用scott使用者的測試表,這個是函數定義情況:

create or replace function test_query_func(dept varchar2)return clobis       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中的代碼:

import cx_Oracle as ora;con = ora.connect(‘scott/[email protected]‘);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對象了:

  empno ename job sal
0 7499 ALLEN SALESMAN 1600
1 7521 WARD SALESMAN 1250
2 7654 MARTIN SALESMAN 1250
3 7698 BLAKE MANAGER 2850
4 7844 TURNER SALESMAN 1500
5 7900 JAMES CLERK 950

本文出自 “kevan的技術手劄” 部落格,請務必保留此出處http://kevan.blog.51cto.com/7204808/1827178

用python讀取oracle函數傳回值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.