1. 程式人生 > >cx_Oracle連接數據庫總結

cx_Oracle連接數據庫總結

是否 username 系統版本 例如 tel 文檔 toc red clas

python中連接oracle數據庫使用第三方庫文件cx_Oracle時遇到了各種問題,網上查找資料調試了幾天才弄好,下面是不斷調試後總結的一些經驗。
1.oracle客戶端(Oracle Instant Client)版本需要和操作系統版本位數相同,同時cx_Oracle官方文檔(http://cx-oracle.readthedocs.io/en/latest/installation.html)上有這樣一段話

Version 12.2 client libraries can connect to Oracle Database 11.2 or greater. Version 12.1 client libraries can connect to Oracle Database 10.2 or greater. Version 11.2 client libraries can connect to Oracle Database 9.2 or greater.
根據安裝的Oracle數據庫版本選擇Oracle客戶端(下載地址 http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html),我安裝的oracle數據庫是11g版本,這裏的客戶端庫在下載客戶端Oracle Instant Client時就包含在內

下載好oracle客戶端後,在客戶端目錄下新建一/network/admin目錄,並在該目錄下新建tnsnames.ora文件,增加自己的數據庫別名配置。
示例如下:

1 MyDB=
2 (DESCRIPTION =
3 (ADDRESS = (PROTOCOL = TCP)(HOST= IP)(PORT = 1521))
4 (CONNECT_DATA =
5 (SERVER = DEDICATED)
6 (SERVICE_NAME = )
7 )
8 )

註意格式要排列好
MyDB為Database名,Host為IP地址, SERVICE_NAME為數據庫服務器的實例名。

2.安裝的python版本位數也需與操作系統版本位數相同

3.安裝的第三方庫cx_Oracle需要版本位數和操作系統相同同時,與Oracle數據庫對應的版本也應相同,因我安裝的數據庫是11g,所以下載的是cx_Oracle-5.3-11g.win-amd64-py3.5-2 若安裝的數據庫是12c則應下載相應版本cx_Oracle(地址 https://pypi.python.org/pypi/cx_Oracle/5.3)

同時可能出現的其他問題在cx_Oracle官方文檔中也寫出了
1. DPI-1047: Oracle Client library cannot be loaded
Check that Python, cx_Oracle and your Oracle Client libraries are all 64-bit or all 32-bit. The DPI-1047 message will tell you whether the 64-bit or 32-bit Oracle Client is needed for your Python.
檢查python,cx_Oracle和Oracle Instant Client版本是否一致,DPI-1047 message會告訴你安裝的客戶端版本是否正確。

2.On Windows, restart your command prompt and use set PATH to check the environment variable has the correct Oracle Client listed before any other Oracle directories.
記得配置Oracle客戶端的環境變量,例如我的配置是 PATH: E:\oracle\instantclient_12_2;

3.On Windows, use the DIR command on the directory set in PATH. Verify that OCI.DLL exists there.
檢查oracle客戶端(instantclient)目錄下存在oci.dll文件

4.On Windows, check that the correct Windows Redistributables have been installed.
oracle客戶端libraries需要正確的Visual Studio版本,具體可見(https://oracle.github.io/odpi/doc/installation.html#windows)中windows目錄下

On Linux, check the LD_LIBRARY_PATH environment variable contains the Oracle Client library directory.
On macOS, make sure Oracle Instant Client is in ~/lib or /usr/local/lib and that you are not using the bundled Python (use Homebrew or Python.org instead).

最後一切就緒,程序未出錯,但並無輸出時感覺內心有些崩潰

 1 import cx_Oracle
 2 
 3 connection = cx_Oracle.Connection("Username/密碼@Host:Port/SERVICE_NAME")
 4 cursor = connection.cursor()
 5 
 6 try:
 7   cursor.execute("select 1 / 0 from dual")
 8 except cx_Oracle.DatabaseError as exc:
 9   error, = exc.args
10 print("Oracle-Error-Code:", error.code)
11 print("Oracle-Error-Message:", error.message)

最後查看意識到是執行了sql語句,但並未進行輸出

cursor.execute("select 1 / 0 from dual")


下一行增加
print(cursor.description)
便可以看見查找到的數據庫中的內容

cx_Oracle連接數據庫總結