Python 关联 Oracle PL/SQL 通常需要使用 `cx_Oracle` 库,这是一个用于连接 Oracle 数据库的 Python 扩展模块。以下是使用 `cx_Oracle` 连接 Oracle 数据库并执行 PL/SQL 的基本步骤:
1. 安装 `cx_Oracle` 库:
```bash
pip install cx_Oracle
2. 编写 Python 代码连接 Oracle 数据库并执行 PL/SQL:
```python
import cx_Oracle
数据库连接信息
dsn_tns = cx_Oracle.makedsn('hostname', 'port', service_name='service_name')
connection = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
创建游标对象
cursor = connection.cursor()
PL/SQL 代码
plsql_code = """
BEGIN
-- PL/SQL 代码块
DBMS_OUTPUT.PUT_LINE('Hello, PL/SQL!');
END;
"""
执行 PL/SQL 代码
cursor.execute(plsql_code)
获取并打印输出结果
for line in cursor:
print(line)
关闭游标和连接
cursor.close()
connection.close()
请确保替换 `'hostname'`、`'port'`、`'service_name'`、`'username'` 和 `'password'` 为你的 Oracle 数据库的实际连接信息。