67543 发表于 2016-7-18 09:24:53

用python读取oracle函数返回值

在oracle中创建一个函数,本来是想返回一个index table的,没有成功。想到文本也可以传输信息,就突然来了灵感,把返回值设置文本格式。

考虑到返回数据量可能会很大,varchar2类型长度吃紧,于是将返回值类型设置为clob。

我是用scott用户的测试表,这个是函数定义情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
ssvarchar2(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测试这个函数的返回值:

1
2
3
begin
   dbms_output.put_line(test_query_func('30'));
end;





输出结果:

1
[('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中的代码:

1
2
3
4
5
6
7
8
9
10
11
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().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对象了:

empnoenamejobsal
07499ALLENSALESMAN1600
17521WARDSALESMAN1250
27654MARTINSALESMAN1250
37698BLAKEMANAGER2850
47844TURNERSALESMAN1500
57900JAMESCLERK950

页: [1]
查看完整版本: 用python读取oracle函数返回值