【Python小笔记】Python连接Oracle数据库——cx_Oracle

参考: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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值