Python连接Oracle,很容易入坑的实现。能查阅的资料并不多,尤其在单纯靠百度找资料,非常吃力,我在入这个坑的时候,还好能使用google,不然真的不知要搞多久。
环境
Oracle数据库版本为11g,系统为window64,python环境为3.6
安装步骤
1.安装cx_oracle
注意不能直接使用 ‘pip install cx_oracle’ 命令下载最新的cx_oracle,因为这样下载的版本太高了,是连不上oracle数据库的11g版本的,比如抛出这个异常。
Oracle Client library is at version 0.0 but version 11.2 or higher is needed
也不会指定cx_oracle的版本,因为pip下载会报错。所以我们要直接去python库中下载exe文件进行离线安装: https://pypi.python.org/pypi/cx_Oracle
因为Orcale11g,所有要找到支持连接Oracle11g的版本。
5.3的版本是支持oracle11g,我们可以文件名中看到
红色框为cx_oracle的版本信息,cx_Oracle版本为5.3
黄色框为支持的数据库版本信息,支持的数据库版本为Oracle11g
蓝色框为支持的系统信息,支持的系统信息为window-amd-64位
绿色框为支持的python版本信息,支持的python版本为3.6.X(X为自然数)
我用的是cx_oracle为:cx_Oracle-5.3-11g.win32-py3.6.exe
安装ox_oracle:
只需要双击cx_oracle.exe就能进行自动安装,cx_oracle会自动查找python的环境变量进行安装。另外python的环境必须要cx_oracle.exe支持的python环境保持一致,比如cx_oracle.exe支持的是3.6.X的,python的环境就需要的3.6.X的,就算python是3.7.X的都会弹出没有找到对应环境的弹出框。还有系统的位数也要对应,系统是64位的,但是cx_orale.exe支持的是32位的,也会弹出没有找到对应环境的弹出框。
2.安装OracleInstantClient
如果没有安装OracleInstantClient就直接使用cx_oracle的话,可能会抛出:
64-bit Oracle Client library cannot be loaded
在 http://www.oracle.com/technetwork/topics/winx64soft-089540.html 上下载对Oracle11g的OracleInstantClient:
{如果安装了的了instantclient-basiclite,有可能会抛出下面异常:
如果安装了的了instantclient-basiclite,有可能会抛出下面异常:
cx_Oracle.DatabaseError: ORA-28547: connection to server failed, probable Oracle Net admin error.
OracleInstantClient是个zip文件,解压出来后:
设置环境变量
然后将instantclient-basic目录的文件复制到python的Lib/site-packages文件夹下,如果不做这一步,也会抛出:
cx_Oracle.DatabaseError: ORA-28547: connection to server failed, probable Oracle Net admin error.
3.新建项目测试
注意引用的python环境是否是1,2步骤所应用的环境,不然1,2步骤做完,也没有效果。
连接oracle时,如果抛出下面异常
ORA-12737 Instant Client Light:unsupported server character set ZHS16GBK
可以加上这段代码:
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
完整代码:
# -*- coding: utf-8 -*-
import cx_Oracle as cx #导入模块
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
if __name__ == '__main__':
con = cx.connect('yidongdudao', 'Ppzx147.', '172.16.19.125:1621/orcl') #创建连接
cursor = con.cursor() #创建游标
cursor.execute("select * from T_B_TESTING") #执行sql语句
data = cursor.fetchone() #获取一条数据
print(data) #打印数据
cursor.close() #关闭游标
con.close() #关闭数据库连接
输出效果:
参考博客:
https://www.jianshu.com/p/705128269605
https://dban00b.wordpress.com/2013/08/19/python-64bit-oracle-instantclient-and-cx_oracle-on-mac/