生成200 个激活码,保存到 MySQL 关系型数据库。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30399353/article/details/76275787

生成验证码效果:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb
import random
import string
import sys

#生成验证码
def codeMaker():
    s = "0123456789" + string.letters
    a = ""
    for i in range(4):
        for i in range(4):
            a += random.choice(s)
        if i < 4:
            a += '-'
    a = a[:-1]
    return a
#保存在文件中
file = open("test.txt",'w')
for i in range(200):
    file.write(codeMaker())
#从文件中读取并保存在str里
file = open("test.txt", "r+")
str = file.read()

# 打开数据库连接
db = MySQLdb.connect("localhost","root","","TESTDB")

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 如果数据表已经存在使用 execute() 方法删除表。
cursor.execute("DROP TABLE IF EXISTS Code")

# 创建数据表SQL语句
sql = """CREATE TABLE Code (
        Codes  CHAR(20) NOT NULL)"""

cursor.execute(sql)
# 关闭数据库连接
db.close()

# 打开数据库连接
db = MySQLdb.connect("localhost","root","","TESTDB" )

# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
for n in range(200):
    sql = "INSERT INTO Code(Codes) VALUES ('%s')" % (str[19*n : 19*n+19])
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        # Rollback in case there is any error
        db.rollback()
# 关闭数据库连接
db.close()
# 关闭文件
file.close()


猜你喜欢

转载自blog.csdn.net/qq_30399353/article/details/76275787