参考:https://oracle.github.io/python-cx_Oracle/index.html
一、安装第三方库cx_Oracle
二、连接oracle数据库
提供账户、密码、监听
import cx_Oracle
#连接数据库(本地)
name='scott'
pwd='123456'
tes='localhost/orcl.16.2.133'
localdb=cx_Oracle.connect(name,pwd,tes)
三、执行语句
#获取该数据库的游标
cur=localdb.cursor()
type(cur)
sql='SELECT * FROM EMP'
#cur执行sql,执行后的新游标一旦fetch就会清空,无法二次使用
res_cur=cur.execute(sql)
type(res_cur)
这里的cur已经包含了执行结果,但是只能用一次,为了避免错误,每次要返回结果的时候,都使用cur.execute(sql)
四、输出结果
1)、输出查询表头
#游标描述
#执行sql之后的cur信息不会像cur内容被清空
cur.description
#列表循环取出标题
title=[i[0] for i in cur.description]
title
2)、输出查询内容
- 1.利用循环逐行打印
#1.利用循环逐行打印
for row in cur.execute(sql):
print(row)
- 2.返回首行
#2.返回首行
print(cur.execute(sql).fetchone())
- 3.返回指定行数
#3.返回指定行数
print(cur.execute(sql).fetchmany(5))
- 4.返回所有行数
#4.返回所有行数
print(cur.execute(sql).fetchall())
3)、创建成DataFrame
import pandas as pd
resdf=pd.DataFrame(cur.execute(sql).fetchall(),columns=title)
resdf