python 連線HANA庫,寫入城鄉劃分程式碼(省市縣鎮鄉村5級)到資料庫
阿新 • • 發佈:2019-01-14
1 import pyhdb,re 2 def get_connection(): 3 conn_obj = pyhdb.connect( 4 host = "xxx.172.1.xxx", #HANA地址 5 port = 30015, #HANA埠號 6 user = "xxxxx", #使用者號 7 password = "xxxxx" #密碼 8 ) 9 return conn_obj 10 def get_mat(conn,exec_str): 11 cursor = conn.cursor()12 cursor.execute(exec_str) #連線表和檢視都可以 13 return cursor 14 conn = get_connection() 15 file_str = 'D:\city_2017.txt' 16 with open(file_str, 'r', encoding='gb18030') as f: 17 lines = f.readlines() 18 for i in lines: 19 try: 20 upsert_str = 'UPSERT HC_BI_DW.BI_DIM_BASE_PROVINCIAL_CITY VALUES ('+str(re.split("\[|]",i)[1])+') WITH PRIMARY KEY;' 21 print(upsert_str) 22 mats = get_mat(conn,upsert_str) 23 conn.commit() 24 except BaseException as e: 25 print('錯誤:', e)