1 def writeToDB(data): 2 try: 3 with conn.cursor() as cur: 4 for i in range(len(data)): 5 # get sql 6 cur.execute(writing_sql) 7 conn.commit() 8 9 except Exception: 10 print('There is exception happened!', Exception) 11 traceback.print_exc() 12 conn.rollback() 13 finally: 14 conn.close() 15 16 conn = pymysql.connect(user="root", password="root", database=write_db, host="127.0.0.1", charset='utf8') 17 for chunk in reader: 18 data = chunk.values 19 db_data = [] 20 for item in data: 21 db_data.append(item[0].split("\t")) 22 db_data = np.array(db_data) 23 writeToDB(db_data)
以前老是報錯,說是Connection Already Close;後來才發現是由於寫法的問題;在writeToDB的函數中,執行完畢後,將會執行final裏面的關閉連接;mysql
可是,其實訪問並無完事,在writeToDB外圍還有一層循環,後續仍是會繼續訪問數據庫,可是此時連接已經關閉,因而致使了這個問題。後來作了調整,在writeToDB的調用層實現了finally,在writeToDB內部只有exception的異常捕捉。sql