step1:下載cx_Oracle模塊,cmd--pip install cx_Oracle
step2:
1 import cx_Oracle #引用模塊cx_Oracle 2 conn=cx_Oracle.connect('truck/******@10.74.**.**:****/****') #連接數據庫 3 c=conn.cursor() #獲取cursor 4 x=c.execute('select sysdate from dual') #使用cursor進行各種操作 5 x.fetchone() 6 c.close() #關閉cursor 7 conn.close() #關閉連接
報錯:cx_Oracle.DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "The specified module could not be found".
原因:本機裝的Python、cx_Oracle都是64位的,Navicat連接的Oracle instantclient版本為32位的,所以連接報錯。
解決方案:下載64位 instantclient---http://jvniu.jb51.net:81/201708/tools/instantclientx64_jb51.rar 或者 http://www.oracle.com/technetwork/database/database-technologies/instant-client/downloads/index.html
操作:下載結束后,解壓至 Navicat根目錄,添加環境變量,重啟連接腳本。
報錯:listener does not currently know of service requested in connect descriptor
原因:參數理解錯誤
#conn=cx_Oracle.connect(‘用戶名/密碼@主機ip地址:端口號/Service Name(SID)') conn=cx_Oracle.connect('truck/******@10.74.**.**:****/****')
正確輸入參數之后,數據庫連接成功
Python連接Oracle如果有中文,可能會出亂碼,可通過以下方法解決
1 import os 2 os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
同時,在Python腳本中,添加一行代碼
# -*- coding: utf-8 -*-