Python连接Oracle数据库是很多业务开发场景中的常见需求,通过合适的驱动库和正确的配置,就能实现稳定高效的数据库交互。

连接前的准备工作
安装驱动库
Python连接Oracle最常用的驱动是cx_Oracle,我们可以通过pip命令直接安装,执行以下命令即可完成安装:
pip install cx_Oracle
配置Oracle客户端
cx_Oracle需要依赖Oracle客户端才能正常工作,你需要下载对应版本的Oracle Instant Client,解压后将路径添加到系统的环境变量中。如果是Windows系统,需要将解压路径添加到PATH变量;如果是Linux系统,需要将路径添加到LD_LIBRARY_PATH变量。
基础连接示例
完成准备工作后,就可以编写连接代码了,以下是一个最简单的连接示例,实现连接Oracle并查询数据:
import cx_Oracle
# 配置数据库连接信息
username = "test_user"
password = "test_password"
host = "127.0.0.1"
port = 1521
service_name = "orcl"
# 拼接连接字符串
dsn = cx_Oracle.makedsn(host, port, service_name=service_name)
# 建立连接
try:
conn = cx_Oracle.connect(user=username, password=password, dsn=dsn)
print("Oracle数据库连接成功")
# 创建游标
cursor = conn.cursor()
# 执行查询语句
cursor.execute("SELECT * FROM user_table WHERE id = 1")
# 获取查询结果
result = cursor.fetchone()
print("查询结果:", result)
# 关闭游标和连接
cursor.close()
conn.close()
except Exception as e:
print("数据库连接失败,错误信息:", e)
常用操作示例
插入数据
插入数据时可以使用参数化查询,避免SQL注入风险,示例代码如下:
import cx_Oracle
username = "test_user"
password = "test_password"
host = "127.0.0.1"
port = 1521
service_name = "orcl"
dsn = cx_Oracle.makedsn(host, port, service_name=service_name)
conn = cx_Oracle.connect(user=username, password=password, dsn=dsn)
cursor = conn.cursor()
# 参数化插入语句
insert_sql = "INSERT INTO user_table (id, name, age) VALUES (:1, :2, :3)"
# 插入的数据
data = (1, "张三", 25)
cursor.execute(insert_sql, data)
# 提交事务
conn.commit()
print("数据插入成功")
cursor.close()
conn.close()
更新数据
更新数据的操作和插入类似,同样使用参数化查询,代码如下:
import cx_Oracle
username = "test_user"
password = "test_password"
host = "127.0.0.1"
port = 1521
service_name = "orcl"
dsn = cx_Oracle.makedsn(host, port, service_name=service_name)
conn = cx_Oracle.connect(user=username, password=password, dsn=dsn)
cursor = conn.cursor()
update_sql = "UPDATE user_table SET age = :1 WHERE name = :2"
cursor.execute(update_sql, (26, "张三"))
conn.commit()
print("数据更新成功")
cursor.close()
conn.close()
常见问题及解决方法
- 报错提示找不到Oracle客户端:检查Oracle Instant Client是否正确解压,环境变量是否配置生效,重启终端或IDE后重试。
- 连接超时:检查Oracle数据库服务是否启动,host、port、service_name是否正确,网络是否通畅。
- 编码问题:可以在建立连接时指定编码参数,例如添加encoding="UTF-8", nencoding="UTF-8"参数解决中文乱码问题。
注意:操作完数据库后一定要关闭游标和连接,避免资源占用;执行增删改操作后需要调用commit()方法提交事务,否则数据不会真正写入数据库。