2025,Python连Oracle最新教程
oralce 连数据库,着实有些复杂,按照网上的其他教程,踩了一堆坑后😡,总算是解决了。
下面我将用oracledb来一步步教你如何连接oralce数据,操作数据库,希望对你有帮助
如果对您有用,受累点个免费的赞👍,谢谢
oracledb是什么?
oracledb 驱动程序是一个开源 Python 模块,用于访问 Oracle 数据库。Python-oracledb 是 cx_Oracle 8.3 的重命名主要版本继任者。cx_Oracle 驱动程序已过时,不应用于新开发。
功能亮点
- 从 PyPI 和其他存储库轻松安装
- 支持多个 Oracle 数据库版本
- 支持 Python 数据库 API v2.0 规范 ,其中包含大量添加和一些排除项
- 适用于通用框架和 ORM
- SQL 和 PL/SQL 语句的执行
- 广泛的 Oracle 数据类型支持,包括 JSON、VECTOR、大对象(
CLOB
和BLOB)
和 SQL 对象绑定 - 连接管理,包括连接池
- Oracle 数据库高可用性功能
- 充分利用 Oracle 网络服务基础设施,包括加密的网络流量
安装
用uv工具
想了解uv工具可以看我另一篇文章 ()[]
bash
uv add oracledb
toml
[project]
name = "pythonproject2"
version = "0.1.0"
description = "Add your description here"
requires-python = ">=3.13"
dependencies = [
"cx-oracle>=8.3.0",
"oracledb>=3.3.0",
]
下载oracle client
下载地址 : Oracle Instant Client Downloads
![[局部截取_20250804_085933.png]]
找到自己需要文件,下面以window为例
![[局部截取_20250804_090013.png]]
查看 oralce 的版本
sql
select *
from V$VERSION;
sql
Oracle Database 11g Release 11.2.0.1.0 - 64bit Production
我这里用 11.2.0.4.0
![[局部截取_20250804_090049.png]]
登录后下载即可
解压后放到某个文件夹下面
![[局部截取_20250804_090323.png]] 准备下工作做完
开始写代码
写在前面,如果你在执行过程中存在问题,可以直接去下面问题部分有没有你遇到的,可以尝试解决解决,我踩过的80%的坑,最大的两个在下面 另外可以去官网查查,看官网是个好习惯。
创建表
sql
create table TEST_USER
(
ID INTEGER,
NAME varchar2(200),
AGE INTEGER
);
insert into TEST_USER values (1, 'Alice', 30);
insert into TEST_USER values (2, 'Bob', 25);
insert into TEST_USER values (3, 'Charlie', 35);
查询
python
import oracledb
# 初始化oracle客户端
oracledb.init_oracle_client(lib_dir=r"D:\Environment\instantclient-basic-windows.x64-11.2.0.4.0\instantclient_11_2")
# 连接到Oracle数据库
connection = oracledb.connect("username/password@ip:port/serviename")
# connection = oracledb.connect("ctts/ctts@127.0.0.1:1521/orcl")
# 创建游标
cursor = connection.cursor()
# 执行查询
cursor.execute("select * from TEST_USER")
# 获取查询结果
result = cursor.fetchall()
# 打印查询结果
for row in result:
print(row,end='\n')
# 关闭游标
cursor.close()
# 关闭连接
connection.close()
结果
arduino
(1, 'Alice', 30)
(2, 'Bob', 25)
(3, 'Charlie', 35)
封装查询函数
python
from oracledb import Cursor
def select(description: str, _cursor: Cursor):
"""
执行查询并打印结果
:param description: 操作描述
:param _cursor: 数据游标
"""
# 执行查询
print('Executing query: ', description)
_cursor.execute("select * from TEST_USER")
# 获取查询结果
result = _cursor.fetchall()
print("")
# 打印查询结果
for row in result:
print(row)
print('' + '-' * 50)
添加
python
import oracledb
oracledb.init_oracle_client(lib_dir=r"D:\Environment\instantclient-basic-windows.x64-11.2.0.4.0\instantclient_11_2")
# 连接到Oracle数据库
connection = oracledb.connect("username/password@ip:port/serviename")
# connection = oracledb.connect("ctts/ctts@127.0.0.1:1521/orcl")
# 创建游标
cursor = connection.cursor()
# 插入数据
cursor.execute("INSERT INTO TEST_USER (ID, NAME,AGE) VALUES (:1, :2,:3)", (4, "Deadline", 30))
connection.commit()
select('插入数据', cursor)
# 关闭游标
cursor.close()
# 关闭连接
connection.close()
arduino
Executing query: 插入数据
(1, 'Alice', 30)
(2, 'Bob', 25)
(3, 'Charlie', 35)
(4, 'Deadline', 30)
更新
python
import oracledb
....
# 更新数据
cursor.execute("UPDATE TEST_USER SET NAME = :1 WHERE ID = :2", ("Updated Name", 4))
connection.commit()
select('更新数据', cursor)
....
结果
arduino
Executing query: 更新数据
(1, 'Alice', 30)
(2, 'Bob', 25)
(3, 'Charlie', 35)
(4, 'Updated Name', 30)
删除
python
import oracledb
....
# 删除数据
cursor.execute("DELETE FROM TEST_USER WHERE ID = :1", (4,))
connection.commit()
select('删除数据', cursor)
...
结果
arduino
Executing query: 删除数据
(1, 'Alice', 30)
(2, 'Bob', 25)
(3, 'Charlie', 35)
问题
问题1
python
Processing c:\....resources\cx_oracle-8.1.0.tar.gz
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... done
Building wheels for collected packages: cx_Oracle
Building wheel for cx_Oracle (pyproject.toml) ... error
error: subprocess-exited-with-error
× Building wheel for cx_Oracle (pyproject.toml) did not run successfully.
¦ exit code: 1
?-> [7 lines of output]
C:\....\2\pip-build-env-806_5jc6\overlay\Lib\site-packages\setuptools\config\expand.py:144: UserWarning: File 'C:\\....\\2\\pip-install-r8jb3ohi\\cx-oracle_111cfa7e3d91425bb65e9a6baa89c82f\\README.md' cannot be found
warnings.warn(f"File {path!r} cannot be found")
running bdist_wheel
running build
running build_ext
building 'cx_Oracle' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for cx_Oracle
Failed to build cx_Oracle
ERROR: Could not build wheels for cx_Oracle, which is required to install pyproject.toml-based projects
- 安装Microsoft C++ Build Toolshttps://visualstudio.microsoft.com/zh-hant/visual-cpp-build-tools/
- 启用后,点击使用 C++的桌面开发再选中以下套:
vs_BuildTools.exe
- MSVCv143-VS 2022 C++ x64/x86建置工...
- Windows 11 SDK (10.0.22621.0)
- 使用於Windows的C++ Cmake工具
问题2
python
When I wanted to install a new package in Pycharm, I did accidentely hit the UnInstall button of the pip package. I tried to reinstall it, but now I seem to have a chicken-egg problem. When I select pip and then Install, I do get following error:
Error: Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2024.3.1.1\plugins\python-ce\helpers\packaging_tool.py", line 85, in run_pip
runpy.run_module(module_name, run_name='__main__', alter_sys=True)
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen runpy>", line 222, in run_module
File "<frozen runpy>", line 142, in _get_module_details
ImportError: No module named pip
Accidentely uninstalled pip, how to recover? -- IDEs Support (IntelliJ Platform) | JetBrains
Just try re-creating a virtual environment and it should work fine.
重新建一个项目,再安装一次oracledb即可,虽然不知道为什么,人家就是这么说的,我试了确实能行🤣
总结
python连oracle着实有些麻烦,写起来倒是还行,主要是网上很多教程大多都是围绕着cx-oracle,为了安装这东西,又安装了另一堆东西,着实麻烦。好在结局是好的。希望对你有用,免的浪费时间。
(对您有帮助 && 觉得我总结的还行) -> 受累点个免费的赞👍,谢谢