python读取oracle函数返回值

yipeiwu_com5年前Python基础

在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对象了:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

django连接mysql配置方法总结(推荐)

最近在学习django,学到第五章模型时,需要连接数据库,然后,在这里分享一下方法。 起初是不知道怎样配置mysql数据库,但是还好,django的官网上面有相关的配置方法,下面就直接...

Python首次安装后运行报错(0xc000007b)的解决方法

Python首次安装后运行报错(0xc000007b)的解决方法

错误提示如下: 其实这是一个挺常见的系统报错,缺乏VC++库。 我安装的是python3.5.2,这个版本需要的vc版本是2015的了,下载:Microsoft Visual C++...

对Python中gensim库word2vec的使用详解

pip install gensim安装好库后,即可导入使用: 1、训练模型定义 from gensim.models import Word2Vec model = Word2V...

使用Python实现画一个中国地图

使用Python实现画一个中国地图

为什么是Python 先来聊聊为什么做数据分析一定要用Python或R语言。编程语言这么多种,Java, PHP都很成熟,但是为什么在最近热火的数据分析领域,很多人选择用Python语言...

判断网页编码的方法python版

在web开发的时候我们经常会遇到网页抓取和分析,各种语言都可以完成这个功能。我喜欢用python实现,因为python提供了很多成熟的模块,可以很方便的实现网页抓取。 但是在抓取过程中会...