批量插入数据,两种方法:
- execute()
- executemany()
executemany()效率远远高于execute(),推荐使用executemany()
代码如下:
1 import MySQLdb 2 3 conn = MySQLdb.connect( 4 host=‘fjkdasjfkdas.aliyuncs.com‘, 5 port=3306, 6 user=‘fdasf‘, 7 passwd=‘fdasfda‘, 8 db=‘datav‘, 9 charset=‘utf8‘ 10 ) 11 12 cur = conn.cursor() 13 14 f = open(‘test.txt‘, ‘rt‘) # 读取文件 15 lines = f.readlines() 16 lists = [] # 定义一个数组 17 for line in lines: 18 s = (str(line.split(‘,‘)[0]),int(line.split(‘,‘)[1])) # 构造一个元组 19 print(s) 20 lists.append(s) # 将元组添加到数组中 21 22 print(lists) 23 cur.executemany(f"insert into zy_1(name, score) values(%s,%s)",lists) # 批量插入 24 conn.commit() 25 26 cur.close() 27 conn.close()