#coding:utf-8 import random import string import MySQLdb def gen_charint(filename, width =4, num=5): f = open(filename, 'wb') charint = string.digits + string.letters for i in range(num): verify = [random.choice(charint) for j in range(width)] verify = ''.join(verify) + '\n' f.write(verify) f.close() def store_mysql(filepath): conn = MySQLdb.connect( host="localhost", port=3306, user='root', passwd='root', db='test', charset='utf8' ) cursor = conn.cursor() # 判斷表是否存在 cursor.execute('show tables in test') tables = cursor.fetchall() findtables = False for table in tables: if 'coupon' in table: findtables = True # 下面的sql語句中的符號為反引號 # 由於剛開始設置code的字段長度偏小,報錯后,調整這里的長度不起作用,查看數據庫並未相應改變,需要手動更改數據庫該字段長度 if not findtables: cursor.execute(''' CREATE TABLE `coupon24`( `id` INT NOT NULL AUTO_INCREMENT, `coupon` VARCHAR(66) NOT NULL, PRIMARY KEY(`id`)); ''') f = open(filepath, 'rb') for line in f.readlines(): code = line.split() cursor.execute('insert into coupon24 (coupon) VALUES (%s)', code) conn.commit() cursor.close() conn.close() if __name__ == '__main__': filename = 'result24.txt' width = 4 num = 11 gen_charint(filename, width, num) store_mysql(filename)
注意點:
1、用列表生成式生成隨機字數和數字,並通過join連接,並注意加上換行符
2、創建表時,表名和字段名均要用反引號,即TAB鍵上方的那個按鍵