Python Test API - 用python連線Oracle資料庫並操作
阿新 • • 發佈:2018-11-14
目的: 通過python連線遠端的一臺oracle資料庫伺服器,並用python程式碼實現增刪改查的操作。本研究是為測試API準備資料庫環境的第一步。
環境配置(如果用64bit的,就都需要64bit):
1. 在本地計算機上安裝好oralce client (64bit)
2. 在本地安裝好python (64bit)
3. 在本地安裝好python的外掛cx_Oracle (64bit)
我需要連線的資料庫的tns如下(位於oracle client下的tnsnames.ora檔案):
ORCL140 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.130.140 )(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = orcl)
)
)
假定使用的賬號密碼為為
ames/123
連線資料庫,增刪改查的示例如下(操作完畢後記得關閉連線和cursor):
import cx_Oracle import time, datetime # -----連線資料庫------------------------------------------ # 連線方法 ames是登入資料庫的使用者名稱; 123是密碼; 192.168.130.140:1521是oracle伺服器所在的地址和埠號 # orcl 是配置在oracle client下tnsnames.ora的SERVICE_NAME conn = cx_Oracle.connect("ames", "123", "192.168.130.140:1521/orcl") cur = conn.cursor() # -----查詢資料庫------------------------------------------ # sql = "SELECT * FROM Ams_User_Scope_Certificate order by ID" # cur.execute(sql) # # # 讀取每行的資料 方法一:用for...in方法 # rows = cur.fetchall() # for row in rows: # print(row) # 讀取每行的資料 方法二:用while方法 # while(True): # row = cur.fetchone() # if row == None: # break # print(row) # 返回行數 # rows = cur.fetchall() # print(cur.rowcount) # -----插入資料------------------------------------------ # dt = datetime.date.today() # dt_1_year_later = dt + datetime.timedelta(days = 365) # # param ={'ID':100000, # 'FORUSER':100000, # 'AUTHORITY':'APITest_authority', # 'LICENCECATEGORY': 'APITest_Licencecategory', # 'HKAAUTHEXPIRYDATE':dt_1_year_later # } # # sql = "insert into Ams_User_Scope_Certificate values (:ID, :FORUSER, :AUTHORITY, :LICENCECATEGORY, :HKAAUTHEXPIRYDATE)" # cur.execute(sql, param) # conn.commit() # -----刪除表中指定行的資料------------------------------------------ # sql = "delete from Ams_User_Scope_Certificate where AUTHORITY like 'APITest%' " # cur.execute(sql) # conn.commit() #------更新指定行的資料-------------------------------------------- # sql = "update Ams_User_Scope_Certificate set HKAAUTHEXPIRYDATE = to_date('2018/8/15', 'YYYY/MM/DD') where AUTHORITY = 'APITest_authority'" # cur.execute(sql) # conn.commit() # -----關閉連線------------------------------------------------ # 操作完畢,關閉 cur.close() conn.close()