Python连接Oracle数据库——cx_Oracle

一、安装第三方库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

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章