Python 访问 Oracle可以通过两种Oracle官方库:
旧驱动:cx_Oracle(需要安装Oracle Instant client)
新驱动:oracledb(Oracle数据库12.1或更高版本不需要安装 Oracle Instant client)
需要安装 Oracle Instant client(Oracle即时客户端)。
GitHub:https://github.com/oracle/python-oracledb
python-oracledb 有两种模式: Thin 和 Thick。
官方下载地址:https://www.oracle.com/database/technologies/instant-client/downloads.html
官方安装手册:https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html#installing-cx-oracle-on-macos-intel-x86
截止目前(20240611), 最新版本instantclient-basic-macos.x64-19.16.0.0.0dbru.dmg 客户端经测试可以访问Oracle 11.2.0.2.0。
以下是在macos上安装 instantclient-basic-macos.x64-19.16.0.0.0dbru.dmg
步骤:
cd $HOME/Downloads
# 1.下载 instantclient-basic-macos.x64-19.16.0.0.0dbru.dmg
# 2.挂载下载的DMG文件
双击 instantclient-basic-macos.x64-19.8.0.0.0dbru.dmg
# 3.默认安装在$HOME/Downloads(如果不介意,则完成后直接跳到第 5 步)
复制全部文件到自定义文件夹
# 4.修改安装文件
vim install_ic.sh
DEST=/Users/${USER}/Downloads/instantclient_19_16
修改为自己创建的目录:
DEST=/Users/wangfugui/home/dev/middleware/数据库/Oracle/instantclient/instantclient_19_16
# 5.安装客户端
sh install_ic.sh
(非必须)如果要安装sdk、sqlplus,按照上面的方法,将文件复制到同一个目录中 instantclient_19_16
,修改目录并执行安装。
需要安装 Oracle Instant client。
import cx_Oracle
cx_Oracle.init_oracle_client(lib_dir="/Users/wangfugui/home/dev/middleware/数据库/Oracle/instantclient/instantclient_19_16")
connection = cx_Oracle.connect(user="oracle", password="oracle",
dsn="localhost/XE")
cursor = connection.cursor()
cursor.execute("""
SELECT first_name, last_name
FROM employees
WHERE EMPLOYEE_ID > :did AND EMPLOYEE_ID < :eid""",
did = 101,
eid = 104)
for fname, lname in cursor:
print("Values:", fname, lname)
Oracle数据库12.1或更高版本不需要安装 Oracle Instant client。
import getpass
import oracledb
un = 'oracle'
cs = 'localhost/XE'
pw = getpass.getpass(f'Enter password for {un}@{cs}: ')
with oracledb.connect(user=un, password=pw, dsn=cs) as connection:
with connection.cursor() as cursor:
sql = """SELECT * FROM employees"""
for r in cursor.execute(sql):
print(r)