可以批量插入数据,批量修改数据等
例如1: 插入6条数据
import MySQLdb conn = MySQLdb.connect( host='192.168.0.0', port=3306, user='abc', passwd='abc', db='abc', charset='utf8' ) cur = conn.cursor() # 插入6条数据 for i in range(100000, 100006): sql = f'insert into test.tb_test (num) VALUES ({i})' cur.execute(sql) conn.commit() cur.close() conn.close()
结果如下:
例2:修改特定列的数据(当id为空时,顺序插入数据)
sql1 = "select * from test.tb_test where id is null" cur.execute(sql1) c = cur.fetchall() nn = len(c) print(nn) # id为null的行有nn个 for n in range(nn): sql2 = f'update test.tb_test set id = {n} where id is null limit 1' cur.execute(sql2) conn.commit()
结果如下: