python - 如何从 Python 访问 Oracle?

标签 python oracle database-connection cx-oracle

如何从 Python 访问 Oracle?我已经下载了一个 cx_Oracle msi 安装程序,但是 Python 无法导入该库。

我收到以下错误:

import cx_Oracle

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import cx_Oracle
ImportError: DLL load failed: The specified module could not be found.

如果有任何帮助,我将不胜感激。

最佳答案

这对我有用。我的 Python 和 Oracle 版本与您的略有不同,但应该采用相同的方法。只需确保 cx_Oracle 二进制安装程序版本与您的 Oracle 客户端和 Python 版本匹配即可。

我的版本:

  • Python 2.7
  • Oracle Instant Client 11G R2
  • cx_Oracle 5.0.4(Unicode、Python 2.7、Oracle 11G)
  • Windows XP SP3

步骤:

  1. 下载 Oracle Instant Client 软件包。我使用了 Instantclient-basic-win32-11.2.0.1.0.zip。解压到 C:\your\path\to\instantclient_11_2
  2. 下载并运行 cx_Oracle 二进制安装程序。我使用了 cx_Oracle-5.0.4-11g-unicode.win32-py2.7.msi。我为所有用户安装了它,并将它指向它在注册表中找到的 Python 2.7 位置。
  3. 通过批处理脚本或在您的应用上下文中有意义的任何机制设置 ORACLE_HOME 和 PATH 环境变量,以便它们指向 Oracle Instant Client 目录。请参阅下面的 oracle_python.bat 源代码。我确信必须有一个更优雅的解决方案,但我想尽可能地限制我的系统范围的更改。确保将目标 Oracle Instant Client 目录放在 PATH 的开头(或至少在任何其他 Oracle 客户端目录之前)。现在,我只做命令行的事情,所以我只是在 shell 中运行 oracle_python.bat,然后再运行任何需要 cx_Oracle 的程序。
  4. 运行 regedit 并检查是否在\HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE 中设置了 NLS_LANG 键。如果是这样,请重命名 key (我将其更改为 NLS_LANG_OLD)或取消设置。该键只应用作 Oracle 7 客户端的默认 NLS_LANG 值,因此删除它是安全的,除非您碰巧在其他地方使用 Oracle 7 客户端。与往常一样,请务必在进行更改之前备份您的注册表。
  5. 现在,您应该可以在 Python 程序中导入 cx_Oracle。请参阅下面的 oracle_test.py 源代码。请注意,对于我的 cx_Oracle 版本,我必须将连接和 SQL 字符串设置为 Unicode。

来源:oracle_python.bat

@echo off
set ORACLE_HOME=C:\your\path\to\instantclient_11_2
set PATH=%ORACLE_HOME%;%PATH%

来源:oracle_test.py

import cx_Oracle

conn_str = u'user/password@host:port/service'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute(u'select your_col_1, your_col_2 from your_table')
for row in c:
    print row[0], "-", row[1]
conn.close()

可能的问题:

  • “ORA-12705:无法访问 NLS 数据文件或指定的环境无效” - 我在更改 NLS_LANG 注册表之前遇到了这个问题。
  • "TypeError: argument 1 must be unicode, not str"- 如果您需要将连接字符串设置为 Unicode。
  • "TypeError: Expecting None or a string"- 如果您需要将 SQL 字符串设置为 Unicode。
  • "ImportError: DLL load failed: 找不到指定的过程。"- 可能表示 cx_Oracle 找不到合适的 Oracle 客户端 DLL。

关于python - 如何从 Python 访问 Oracle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3521692/

相关文章:

python - 如何使用 StreamHandler 捕获记录器 stderr 上的输出?

python - argparse 有没有办法允许第一个位置参数不仅是无破折号,而且是多个可能的用户输入值之一?

multithreading - 尝试插入 Oracle DB 时,Java 线程永远保持锁定状态

oracle - ServiceStack 中的 Dapper 和 OrmLite IDBConnectionFactory

mysql - Excel VBA连接Linux服务器上的MySQL

python - distutils 可以将模块/包安装为可执行脚本吗?

Python 列表 : How to sort by timestamp?(App Engine 相关)

Windows 上的 PHP PDO 安装(xampp)

c# - 为什么该类成员保持 SQL 连接打开?

java - 如何允许桌面应用程序访问 Microsoft 服务器上的 MySQL 数据库?