一、准备工作
1. 安装驱动库
推荐使用Oracle官方维护的oracledb
驱动(原cx_Oracle
的升级版):
pip install oracledb
2. 安装Oracle客户端
- 下载Oracle Instant Client(基础版即可):
https://www.oracle.com/database/technologies/instant-client.html - 解压后设置环境变量:
# Linux/macOS export LD_LIBRARY_PATH=/path/to/instantclient_21_13:$LD_LIBRARY_PATH # Windows set PATH=C:\instantclient_21_13;%PATH%
二、基础连接方式
1. 直接连接
import oracledb
# 连接参数
dsn = {
"user": "your_username",
"password": "your_password",
"dsn": "hostname:port/service_name"
}
# 建立连接
with oracledb.connect(**dsn) as connection:
cursor = connection.cursor()
# 执行查询
cursor.execute("SELECT * FROM employees WHERE department_id = :dept_id",
dept_id=50)
# 获取结果
for row in cursor:
print(row)
2. 使用连接字符串
conn = oracledb.connect(
user="scott",
password="tiger",
dsn="localhost:1521/ORCLCDB"
)
三、高级功能
1. 连接池配置
pool = oracledb.create_pool(
user="hr",
password="hr_password",
dsn="dbhost:1521/orclpdb1",
min=2,
max=5,
increment=1
)
with pool.acquire() as conn:
# 使用连接...
2. 数据类型处理
# 处理CLOB
cursor.execute("SELECT large_text FROM documents WHERE id=1")
clob_data = cursor.fetchone()[0].read()
# 处理日期
cursor.execute("SELECT hire_date FROM employees")
for (hire_date,) in cursor:
print(hire_date.strftime("%Y-%m-%d"))
四、常见问题解决
1. DPI-1047错误
现象:无法找到Oracle客户端库
解决方案:
- 确认Instant Client已正确安装
- 检查环境变量设置
- 使用thick模式(需完整客户端):
oracledb.init_oracle_client(lib_dir=r"C:\instantclient_21_13")
2. 中文乱码问题
# 设置字符集
conn = oracledb.connect(
...,
encoding="UTF-8",
nencoding="UTF-8"
)
3. 批量插入优化
data = [(1, 'Alice'), (2, 'Bob'), (3, 'Charlie')]
cursor.executemany(
"INSERT INTO users (id, name) VALUES (:1, :2)",
data,
batcherrors=True # 允许部分失败
)
五、最佳实践建议
-
安全规范:
- 使用环境变量存储凭证
import os user = os.getenv('ORACLE_USER') password = os.getenv('ORACLE_PASSWORD')
-
连接管理:
# 使用with语句自动管理连接 with oracledb.connect(...) as conn: with conn.cursor() as cursor: # 操作数据库
-
性能优化:
- 启用结果集缓存
- 合理使用fetchsize参数
cursor.arraysize = 100 # 每次获取100行
六、扩展阅读
- Oracle官方文档:https://oracle.github.io/python-oracledb/
- 连接字符串格式参考:https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html
希望这篇指南能帮助您顺利实现Python与Oracle的交互!实际开发中建议结合具体业务需求选择连接方式,并做好异常处理机制。