安装环境:win2008 32位,oracle 10.2.0.1.0 ,oracle instantclient 11.2,Python 3.6
C:\oracle_test>pip install cx_Oracle
Collecting cx_Oracle
Using cached https://files.pythonhosted.org/packages/ad/cc/05dcdb2e63274231c82
678057ae685220161e296c2b1c0f85783f8b69913/cx_Oracle-7.0.0-cp36-cp36m-win32.whl
Installing collected packages: cx-Oracle
Successfully installed cx-Oracle-7.0.0
由于该服务器已经有应用在使用oracle 10的客户端,所以,安装了oracle11的即时客户端到 c:\instantclient_11_2 后,并没有设置到PATH里去,而是仅仅提供给python写的程序使用。
import os
import cx_Oracle
#os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' ##保证字符集一致
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.ZHS16GBK'
os.environ['path'] = 'C:\instantclient_11_2' ##使用即时客户端避免版本不兼容
#连接数据库
db=cx_Oracle.connect('db_username/db_userpasswd@localhost:1521/orcl')
print("oracle版本:", db.version)
#创建游标
cursor = db.cursor()
#执行SQL
cursor.execute("select username,rolename from tb_user where userid>='001' and userid <='099' ")
#获取数据
data=cursor.fetchall()
print(data)
print(type(data))
#关闭游标
cursor.close()
#断开数据库
db.close()