標籤:應用程式 oracle python
環境:
作業系統:win7 64位,CPU是inter的pc機
Oracle服務端:Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
Oracle本地用戶端:Release 11.2.0.1.0 32bit Production
Python版本:python2.7.5 (安裝路徑:C:\Python27\)
cx_Oracle版本:cx_Oracle-5.2.1-11g.win-amd64-py2.7.exe
Iinstantclient版本:instantclient-basic-win-x86-64-11.2.0.1.0.zip
在學習python過程中,需要串連oracle資料庫,所以要安裝cx_Oracle。
安裝cx_Oracle-5.2.1-11g.win-amd64-py2.7.exe,import cx_Oracle報錯。提示:import cx_Oracle
ImportError: DLL load failed: %1 不是有效 Win32 應用程式。根據報錯提示應該是缺少dll檔案,因為我本機oracle用戶端是32位的,64位的cx_Oracle程式調用32位的動態庫肯定會報錯。
根據文章http://blog.csdn.net/huzhenwei/article/details/3946308指點,去oracle網站下載了instance client,地址是:
http://www.oracle.com/technology/software/tech/oci/instantclient/index.html。
我下載了instantclient-basic-win-x86-64-11.2.0.1.0.zip這個版本。
直接解壓C:\instantclient_11_2 目錄下。
在“環境變數”的“系統變數”中增加:
ORACLE_HOME = C:\instantclient_11_2 (網上說需要,但是測試不加也可以)
TNS_ADMIN = C:\instantclient_11_2 (網上說需要,但是測試不加也可以)
NLS_LANG = SIMPLIFIED CHINESE_CHINA.ZHS16GBK
修改Path變數,在後面添加 C:\instantclient_11_2
然後把解壓包中的oci.dll檔案放到%python_home%\Lib\site-packages 下,再次import不會報錯了。
執行測試python指令碼報錯,提示cx_Oracle Interface Error: Unable to acquire Oracle enviroment handle。啟動PLSQL登陸開啟的是剛才的tns,但登陸就報錯ORA-1以為是instance client和之前安裝的32位oracle client衝突,ORA-12557。感覺是這個64位的instance client與之前裝的32位oracle client衝突了。於是把環境變數裡的ORACLE_PATH刪掉,就可以登陸PLSQL了。但測試語句還是報那個錯。折騰了半天,最後死馬當活馬醫吧,嘗試著把C:\instantclient_11_2裡面的dll檔案都拷貝到了python的C:\Python27\Lib\site-packages目錄下,又RUN了一下,居然不報錯了。 然後逐個刪掉,最後發現oraociei11.dll刪掉會報錯,而其它dll刪掉重新Run都不會報錯。
不過使用PLSQL登陸還是會報錯,只好把環境變數ORACLE_HOME刪掉了,並不影響cx_Oracle的使用。原理不太清楚,先記錄下來。
Python測試指令碼:
#!/usr/bin/python#coding=utf-8import cx_Oracleusername = "smb"passwd = "czty_smb"host = "192.168.150.233"port = "1521"sid = "zsms"dsn = cx_Oracle.makedsn(host, port, sid)con = cx_Oracle.connect(username, passwd, dsn)cursor= con.cursor()sql = ‘SELECT smbms, prtms FROM t_user_mobile_dz‘cursor.execute(sql)result = cursor.fetchall()print "Total: " + str(cursor.rowcount)for row in result:print rowcursor.close()con.close()
python串連oracle配置