用Python读取Oracle函数返回值
在Oracle中创建一个函数,本来是想返回一个index table的,没有成功。想到文本也可以传输信息,就突然来了灵感,把返回值设置文本格式。
考虑到返回数据量可能会很大,varchar2类型长度吃紧,于是将返回值类型设置为clob。
我是用scott用户的测试表emp,这个是函数定义情况:
1 create or replace function test_query_func(dept varchar2) 2 return clob 3 is 4 type test_record is record 5 (rec_empno emp.empno%type, 6 rec_ename emp.ename%type, 7 rec_job emp.job%type, 8 rec_sal emp.sal%type); 9 type test_query_arr is table of test_record index by binary_integer; 10 cursor cur is select empno, ename, job, sal from emp where deptno = dept; 11 test_query test_query_arr; 12 i integer := 0; 13 ss varchar2(200) := ''; 14 res clob := '['; 15 begin 16 for c in cur loop 17 i := i + 1; 18 test_query(i) := c; 19 end loop; 20 for q in 1..test_query.count loop 21 ss := '(''' || test_query(q).rec_empno || ''', ''' || test_query(q).rec_ename || ''', ''' || test_query(q).rec_job || ''', ''' || test_query(q).rec_sal || ''')'; 22 if q < test_query.count then 23 ss := ss || ','; 24 end if; 25 res := res || ss; 26 end loop; 27 res := res || ']'; 28 return res; 29 end;
可以在pl/sql developer测试这个函数的返回值:
1 begin 2 dbms_output.put_line(test_query_func('30')); 3 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库:
1 import cx_Oracle as ora; 2 con = ora.connect('scott/scott@oradb'); 3 cur = con.cursor(); 4 cur.execute('select test_query_func(30) from dual'); 5 res = cur.fetchall()[0][0].read(); 6 cur.close(); 7 con.close(); 8 data = eval(res); 9 import pandas as pd; 10 df = pd.DataFrame(data, columns = ['empno', 'ename', 'job', 'sal']); 11 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 |
相关推荐
83510998 2020-07-18
thickbookszone 2020-06-14
xiaonamylove 2020-06-14
天高任鸟飞 2020-06-04
Magicsoftware 2020-06-01
Reiki 2020-05-04
小菜鸟的代码世界 2020-05-04
whynotgonow 2020-04-26
zcyuefan 2020-04-19
神龙 2020-02-10
ajaxtony 2020-02-03
HongKongPython 2020-01-30
GoatSucker 2020-01-24
liuyang000 2020-01-24
zhiyuan0 2020-01-06
狼窝 2019-12-12