- 环境准备
- cx_Oracle
- instantclient
- wimdow安装
- linux下安装
- python连接
python连接oracle需要导入cx-Oracle库,同时需要安装instantclient,进行配置。
cx_Oracle使用pip安装即可。
instantclient若只安装cx-Oracle,不安装该客户端,进行数据库操作,会导致:使用cx_Oracle连接数据库时报错: cx_Oracle.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library
wimdow安装- 去官网下载instantclient,注意版本64、32位,提供一个链接:https://www.oracle.com/cn/database/technology/instant-client.html
- 安装,配置环境变量。在系统变量中,添加TNS_ADMIN
- 将instantclient目录下的三个指定dll文件复制到python安装目录下
1.指定一个目录(例如instantclient),下载三个文件,(可以下载再复制到linux下)http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html
instantclient-basic-linux.x64-11.2.0.4.0.zip
instantclient-sdk-linux.x64-11.2.0.4.0.zip
instantclient-sqlplus-linux.x64-11.2.0.4.0.zip
2.解压,unzip ****.zip。若出现No package unzip available,需要找到支持的版本,命令为:yum search unzip。
==================== N/S matched: gcc-c++ ================================================================================================================ unzip.x86_64 : **** Name and summary matches only, use "search all" for everything.
yum install unzip.x86_64
3.解压缩这三个文件.这会给你一个目录instantclient_11_2/
4.添加环境变量,cd到根目录,执行vim /etc/profile 并在打开的文件末尾添加
export ORACLE_HOME=/software/instantclient_11_2 export PATH=$ORACLE_HOME:$PATH export TNS_ADMIN=$ORACLE_HOME/network/admin export LD_LIBRARY_PATH=$ORACLE_HOME:$LD_LIBRARY_PATH export NLS_LANG='SIMPLIFIEDCHINESE_CHINA.AL32UTF8'
5.执行 source /etc/profile 使配置生效
6.若只是通过代码进行连接oracle操作,可以不配置tnsnames.ora。若需要,则在第4步前执行以下操作:instantclient_11_2下建立目录“/network/admin”,创建文件:“tnsnames.ora”,并添加:
ORCL =
(DEscriptION =
(ADDRESS = (PROTOCOL = TCP)(HOST = ip)(PORT = port)) #填写oracle所在服务器的ip和监听端口
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
python连接
import pandas as pd import cx_Oracle config = "admin/password@ip:port/server" db = cx_Oracle.connect(config) cursor = db.cursor() sql = "'" cursor.execute(sql) re = cursor.fetchall() df = pd.Dataframe(list(re)) cursor.close() db.close()



