1 思路:连接数据库-获取游标-拼好sql-执行sql-提交数据-关闭游标-关闭链接 2 import MySQLdb,time,pprint 3 import random 4 t = int(time.time()) 5 #链接数据库 6 connection = MySQLdb.connect(host="127.0.0.1", 7 user="songqin", 8 passwd='songqin', 9 db='plesson', 10 charset = "utf8") 11 #获取游标 12 c = connection.cursor() 13 sql = "select * from sq_course" 14 for i in range(1,11): 15 names = random.choice(['语文','数学','外语','物理','化学'])+str(i) 16 descs = "课程描述"+str(i) 17 idx = str(i) 18 sql1 = "INSERT INTO sq_course (name,`desc`,display_idx) VALUES('%s','%s','%s');" %(names,descs,idx) 19 #执行SQL 20 raw = c.execute(sql1) 21 #插入数据完后提交数据 22 connection.commit() 23 24 raw1 = c.execute(sql) 25 pprint.pprint(c.fetchall()) 26 #关闭游标 27 c.close() 28 #连接关闭 29 connection.close()