Ubuntu22.04系统python链接Oracle数据库

369 阅读1分钟

本周,笔者在学习vanna.ai的时候,用到了Ubuntu系统下,python链接Oracle数据库的需求。经过两天的学习摸索,终于能链接成功了。得到了两个教训,记录一下。

之前建立conda虚拟环境的时候,习惯了python=3.11,结果pip install cx_Oracle后,运行后,发现报找不到cx_Oraclede模组:

ModuleNotFoundError: No module named 'cx_oracle' 检查后发现,cx_Oracle包最新支持到python3.10,官方地址解释cx_Oracle Release Notes — cx_Oracle 8.3.0 documentation (cx-oracle.readthedocs.io)

新的oracle链接已经更新为oracledb,无奈python -m pip install oracledb这个包,运行后发现,也报错

DPY-4011: the database or network closed the connection 去官方地址解释24. Troubleshooting Errors — python-oracledb 2.1.0b1 documentation 需要设定为Thick mode,笔者不能修改远程的Oracle数据库,无奈删除原来的虚拟环境,新建为python-3.10的环境,安装cx_Oracle,经过一番折腾,终于成功链接,如下是一段测试链接的代码

import cx_Oracle

conn = cx_Oracle.connect("username", "password", "Db_Host/Db_name")
cursor = conn.cursor()
cursor.execute('SELECT sysdate FROM dual')
for row in cursor:
    print(row)
cursor.close

分享出来,供大家后续少走弯路。。