时间:2021-07-01 10:21:17 帮助过:9人阅读
安装了mysql,python3.0先装好pymysql,在IDLE中测试下import pymysql是否报错,没有报错,完美。
1 import pymysql 2 db = pymysql.connect("localhost", "root", "", "test") 连接test数据库 3 cursor=db.cursor() 4 cursor.execute(sql语句) 5 db.commit() 6 db.close()
1 #!/user/bin/python 2 #-*-coding:UTF-8 *-* 3 4 import pymysql 5 import random,string,uuid 6 7 def generateN(len, count, cursor, db, database): 8 getChars = lambda: string.ascii_letters+string.digits 9 generate = lambda len: "".join(random.sample(getChars(), len)) 10 for i in range(count): 11 sql = "insert into {0} (id,value) values ({1},‘{2}‘)".format(database,"null", generate(len)) 12 cursor.execute(sql) 13 db.commit() 14 15 #generateN(10, 20) 16 db = pymysql.connect("localhost", "root", "", "hst") 17 cursor = db.cursor() 18 cursor.execute("drop table if exists generateCodes") 19 sql = "create table generateCodes(id int auto_increment primary key, value varchar(50))" 20 cursor.execute(sql) 21 cursor.execute("show tables"); 22 generateN(10, 20, cursor, db, "generateCodes") 23 db.close()
期间出了2个问题
问题1:pymysql.err.InternalError: (1054, "Unknown column ‘***‘ in ‘field list‘")
参考:https://blog.csdn.net/fk103/article/details/80139284,原因是字符串占位符那里没有写‘‘,将(values ({1},{2})修改为(values ({1},‘{2}‘))
问题2:插入第2个数据的时候Duplicate entry for key ‘PRIMARY‘
参考:https://blog.csdn.net/m0_37664906/article/details/79612006,主键重复了,将(database,i,**)修改为(database,"null",**)
执行脚本后,在控制台中查看表内容
1 select * from generateCodes;
好,结束。
【python练习册】1.3 将1.2题生成的n个激活码保存到mysql关系型数据库中
标签:ase varchar letter t权限 test delete coding auto commit