Python——生成激活码并存入MySQL

xiaoxiao2021-02-28  6

#引入pymysql import pymysql #连接数据库 conn = pymysql.connect(user='root',password='password',database='test') cursor = conn.cursor() #执行 mysql语句 cursor.execute('''create table if not exists actcode( id smallint primary key, code varchar(50) not null); ''') cursor.execute('delete from actcode') #循环执行insert语句 for i,_code in enumerate(codelist): cursor.execute('insert actcode(id,code) values (%s,"%s")'%(i,_code)) conn.commit() cursor.close() conn.close() #目标:200个16个大小写英文、数字组成的激活码 #类似xxxx-xxxx-xxxx-xxxx import random,string CHRLIST=string.ascii_letters+string.digits codelist=[] def many_code(lens,n): c=0 while True: code=single_code(lens) if code in codelist: c=c else: codelist.append(code) c=c+1 if c==n: break print(len(codelist)) def single_code(lens): code='' for x in range(lens): i=random.randint(0,CHRLIST.__len__()-1) code+=CHRLIST[i] return '-'.join(code[i:i+4] for i in range(0,len(code),4)) #many_code(长度,激活码数量) many_code(16,200)

首先,需要安装pymysql,pip3 install pymysql 注意,语句操作后要conn.commit()

转载请注明原文地址: https://www.6miu.com/read-250027.html

最新回复(0)