用python把随机码保存到MySQL数据库中

实现代码:

import random
import pymysql #导入驱动
#连接数据库
connection = pymysql.connect(host='localhost',
                            user='root',
                            password='password',
                            database='test',
                            charset='utf8',
                            cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
#创建表code
cursor.execute("CREATE TABLE CODE(ID int(255) NOT NULL PRIMARY KEY,RANDOMCODE VARCHAR(20) NOT NULL,STATUS int(1) NOT NULL)")
str = ''
char = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(char)
for keys in range(200):
    for v in range(20):
        str += random.choice(char)
    #print(str)
    #插入记录
    cursor.execute("INSERT INTO CODE (ID,RANDOMCODE,STATUS) VALUES (%s,%s,%s)",[keys,str,1])
    str = ''
#提交事务
connection.commit()
#关闭连接
connection.close()

用cmd查询结果如下:

用python把随机码保存到MySQL数据库中_第1张图片

你可能感兴趣的:(python,python,mysql,random,数据库)