Python每日一题(第0002题)
题目:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#coding=utf-8 import MySQLdb import random,string def password(len): chars = string.ascii_letters.lower() + string.digits return ''.join(random.sample(chars,len)) def insertcdkey(): number = 1 for i in range (200): passwd = password(10) cur.execute('insert into jihuoma (id, cdkey) values (%s, %s)', [number, passwd]) number += 1 #print number,passwd if __name__ == '__main__': conn = MySQLdb.connect( host = 'localhost', port = 3306, user = 'root', passwd = '', db = 'test') cur = conn.cursor() cur.execute("create table jihuoma(id varchar(20) primary key,cdkey varchar(20))") insertcdkey() cur.close() conn.commit() conn.close() |
笔记:MySQL的SQL占位符是%s
;