1、背景python
有4張表,每張表要插入多條測試數據。如若還有同種需求,因而寫了一個腳本,來添加數據。
mysql
2、代碼sql
#--coding:utf8-- import pymysql class InsertTestData(object): STUDENT_FILE = 'Student.txt' COURSE_FILE = 'Course.txt' TEACHER_FILE = 'Teacher.txt' SCORE_FILE = 'Score.txt' def __init__(self): self.connect = pymysql.Connect( host = 'localhost', port = 3306, user = 'root', # passwd = ' ', charset = 'utf8' ) self.database = 'execersise_test' def read_lines(self, filename): dict = {} file_name = filename.split('.')[0] dict['file_name'] = file_name with open(filename) as f: lines = f.readlines() dict['file_content'] = lines return dict def connect_mysql(self): cursor = self.connect.cursor() return cursor def close_mysql(self): self.connect.close() def close_curser(self): self.connect_mysql().close() def add_test_datas(self, file_obj): file = file_obj file_name = file['file_name'] title = file['file_content'][0].strip() datas = file['file_content'][1:] content_len = len(datas) data = '' counter = 1 for tmpdata in datas: if counter == content_len: data += '(' + tmpdata.strip() + ');' else: data += '(' + tmpdata.strip() + '),' counter += 1 sql = 'insert into ' + self.database + '.' + file_name + ' (' + title + ') values '+ data try: # self.connect_mysql().executemany(sql) self.connect_mysql().execute(sql) except Exception as e: print('add_' + file_name + ' error: ', e) self.connect.commit() self.close_curser() if __name__ == '__main__': testdata = InsertTestData() testdata.add_test_datas(testdata.read_lines(InsertTestData.STUDENT_FILE)) testdata.add_test_datas(testdata.read_lines(InsertTestData.TEACHER_FILE)) testdata.add_test_datas(testdata.read_lines(InsertTestData.COURSE_FILE)) testdata.add_test_datas(testdata.read_lines(InsertTestData.SCORE_FILE))
在main函數中,只須要指定要讀取的文件,便可快速插入測試數據。
數據庫
爲了便於構造sql語句,定義的數據文件格式以下:
ide
`SID`,`CID`,`Degree` '103' , '3-245' , '86' '105' , '3-245' , '75' '109' , '3-245' , '68' '103' , '3-105' , '92' '105' , '3-105' , '88' '109' , '3-105' , '76' '101' , '3-105' , '64' '107' , '3-105' , '91' '108' , '3-105' , '78' '101' , '6-166' , '85' '107' , '6-166' , '79' '108' , '6-166' , '81'
3、遇到的問題函數
UnicodeDecodeError: 'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence測試
緣由:文件編碼不是ANSI;編碼
解決方法:將文件用notepad打開,另存,編碼設置爲ANSI格式。code
入庫的中文信息亂碼,顯示爲'?'ip
緣由:在建立數據庫時,未將charset設置爲utf8;
解決方法:重建數據庫,重建表,數據庫和表的charset都設置爲utf8
如何將sql的values數據構形成‘(),(),();‘的格式
解決方法:增長計數器,當讀取到最後一行時,以‘;’結尾
如何經過讀取一個文件,同時獲取要操做的表名稱、列名、values
解決方法:
數據文件的文件名稱,定義成表名;
數據文件的titile,即第一行內容,定義成表的列;
數據文件的內容,即第一行以後的內容,定義成表的數據。