使用Python連結Oracle,利用cx_Oracle
Oracle client install這裡就不說明,可以google搜尋如何安裝。
Oracle tnsnames.ora 檔案範例,要注意的三個地方 Host Name/Port Number/Service Name,填入Python程式中。
SYSTEM_OCON =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = Host Name)(PORT = Port Number))
(LOAD_BALANCE = YES)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = Service Name)
(FAILOVER_MODE =
(TYPE = SELECT)
(METHOD = BASIC)
(RETRIES = 180)
(DELAY = 5)
Python 連結程式:
import cx_Oracle
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')
dsn_tns = cx_Oracle.makedsn('Host Name', 'Port Number', service_name='Service Name')
conn = cx_Oracle.connect(user=r'User Name', password='Personal Password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select * from database.table')
for row in c:
print (row[0], '-', row[1])
conn.close()
程式參考
以上這一個連接語法可以成功。
底下使用方式,會一直出現錯誤無法連接Oracle資料庫。
connection = cx_Oracle.connect('使用者名稱/密碼@主機名稱/服務名稱', encoding='UTF-8', nencoding='UTF-8')