cx_Oracle鏈接數據庫總結

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

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

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爲數據庫服務器的實例名。github

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

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會告訴你安裝的客戶端版本是否正確。windows

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文件oracle

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目錄下spa

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) 即可以看見查找到的數據庫中的內容

相關文章
相關標籤/搜索