python链接oracle/plsql数据库 ,查询功能(query) 用cursor fetchall

1. 准备工作

下载安装Oracle instant client

先在”开始“里搜一下有没有instantclient这个文件夹,如果有的话,就不用下载。
oracle instant client 64bit官方下载地址
python链接oracle/plsql数据库 ,查询功能(query) 用cursor fetchall_第1张图片
选择12.2的base package。下载钱可以看一下自己是不是64bit

cx_Oracle 下载安装

现尝试在terminal 里输入pip install cx_Oracle
如果报错的话,可以到官方下载适合自己的版本。

下载地址:https://pypi.org/project/cx-Oracle/#files

python链接oracle/plsql数据库 ,查询功能(query) 用cursor fetchall_第2张图片

要根据自己的电脑数位,和python版本选择相应的whl文件。

(cp37对应的是python 3.7)

下载完之后,打开cmd进入到whl文件所在的目录。输入:
pip install cx_Oracle-8.0.0-cp37-cp37m-win_amd64.whl

后面改成你文件的名称

查看自己的环境 & 配置

在“开始”搜tnsnames.ora 打开这个文件可以看自己的部分参数
python链接oracle/plsql数据库 ,查询功能(query) 用cursor fetchall_第3张图片

数据库的ip

默认是172.0.0.1

oracle 用户名 密码

如果自己没有建,默认的是:
用户名:system 密码:manager

port端口

默认是1521

service name(database name)

默认是orcl

sql上准备一个可以query的table

2. Python上的操作

链接db

import cx_Oracle
db = oracle.connect('username/[email protected]:1521/orcl')
#这里替换成自己的用户名和密码
# 如果不是本地数据库的话,127.0.0.1和端口也要更改
# orcl改成自己的service_name
# username/password@ip_address:port/service_name
print("successfully connected to oracle database")

query

query = "select * from table_name"
cursor = db.cursor() # 创建cursor
cursor.execute(query)
data = cursor.fetchall()
# 如果只要一行的话 fetchall改成fetchone()
cursor.close() #记得关cursor和db
db.close()

输出的data长这样,可以直接变成pandas dataframe

[(63133, '6406', '83237', '1', '95471', '170.0'),
 (313401, '6406', '83237', '1', '87331', '199.0'),
 (248909, '392', '83237', '1', '32233', '38.0'),
 (208458, '392', '83237', '1', '174374', '139.0')]

保存到本地csv

import pandas as pd
df = pd.DataFrame(data)
df.to_csv(filename)

table表头问题

cursor没办法顺带显示表格抬头,需要通过另外一个query找到表格的column heads:
sql里的query

select COLUMN_NAME 
from user_tab_columns 
where TABLE_NAME='TABLE_NAME';

python里:

table_name = "AD_FEATURE" #这里替换成自己的table name
query = "select * from" + table_name
cursor = db.cursor()
cursor.execute(query)
data = cursor.fetchall()
print(data)
#获取表头

columnsname = cursor.execute(
"select COLUMN_NAME from user_tab_columns where TABLE_NAME='"+table_name+"'").fetchall()
# 注意table name必须全部大写
df = pd.DataFrame(data)
df.columns = [i[0] for i in columnsname]
display(df)

输出:

python链接oracle/plsql数据库 ,查询功能(query) 用cursor fetchall_第4张图片

但是还是没有办法解决如果query涉及到多个table,该如何显示抬头。
edit:已解决 请查看这篇文章
如何查看column heads

你可能感兴趣的:(数据库)