操作系統(tǒng)版本:
macOS High Sierra 10.13 Beta
Python版本:
Python 3.6.0
macOS 默認Python 版本為2.7,為了不更改系統(tǒng)默認版本,可采用官網(wǎng) pkg 安裝包安裝 Python3。https://www.python.org/downloads/
Python3 cx_Oracle 測試代碼:
import cx_Oracle as orcl
print("cx_Oracle.version:", orcl.version)
host = "192.168.1.250"
port = "1521"
sid = "ORCL"
dsn = orcl.makedsn(host, port, sid)
connection = orcl.connect("odb1", "odb1", dsn)
cursor = orcl.Cursor(connection)
print("======")
sql = "select count(1) as total from ACCOUNT"
res = cursor.execute(sql)
print(res.fetchone())
print("======")
安裝 cx_Oracle
https://pypi.python.org/pypi/cx_Oracle/
目前 cx_Oracle 版本為 6.0rc1 ,可以采用 pip 進行安裝
https://oracle.github.io/python-cx_Oracle/
pip3 install cx_Oracle --pre
(因在 mac 下安裝的 python3 所以需使用 pip3 進行安裝)
安裝完成后可以運行代碼進行測試,報錯如下:
Traceback (most recent call last):
File "/Users/wanghuan/iCode/Python/HelloPython/runorcale.py", line 1, in <module>
import cx_Oracle
cx_Oracle.DatabaseError: DPI-1047: Oracle Client library cannot be loaded: dlopen(libclntsh.dylib, 1): image not found. See https://oracle.github.io/odpi/doc/installation.html for help
根據(jù)提示查看:https://oracle.github.io/odpi/doc/installation.html
找到 macOS 安裝說明 :
Download the 11.2 or 12.1 “Basic” or “Basic Light” zip file from here. Choose either a 64-bit or 32-bit package, matching your application architecture. Most applications use 64-bit.
需下載相應(yīng)的 Instant Client Package 包文件,點擊 here 進入 http://www.oracle.com/technetwork/topics/intel-macsoft-096467.html
找到相應(yīng)的版本,我下載的是 instantclient-basic-macos.x64-11.2.0.4.0.zip (此處下載需要有 Oracle 網(wǎng)站用戶賬號,根據(jù)提示免費注冊即可,登錄后回到下載頁,同意協(xié)議,進行下載即可)
下載完成后根據(jù) https://oracle.github.io/odpi/doc/installation.html#macos 說明進行安裝
在終端中通過命令在 home 下新建 lib 文件夾 mkdir ~/lib, 然后將下載的zip包解壓,全部文件復(fù)制到 ~/lib 文件夾下即可
測試代碼運行結(jié)果如下:
cx_Oracle.version: 6.0rc1
======
(166079,)
======
如果出現(xiàn)cx_Oracle.DatabaseError: ORA-21561: OID generation failed錯誤,需要配置 hosts 文件
通過終端查看 hostname
hostname
xxxMacBook.local
將 hostname 結(jié)果填加至 /etc/hosts 最后一行即可
sudo vim /etc/hosts
127.0.0.1 xxxMacBook.local