Python每天练习——小程序003

题目003:将 002 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库和 Redis 非关系型数据库中。

思路: 新手建议先去学学python如何操作mysql数据库,这个教程很清晰教你如何连接数据库,如何创建数据库表,还有插入,查询,更新,删除等操作。想简单学习一下mysql,推荐一个挺好的教程MySQL教程

本练习运行环境为ubuntu+pycharm+Python2.7;还没安装MySQL的可以直接在pycharm下方的运行命令:pip install MySQL-python   来安装mysql。建议尽量在linux系统下操作mysql,同时新手需要注意的是运行本例子最好是用Python2的版本,不然在安装mysql时会出错。---本人是新手,说的有错的地方勿喷。。。

#!/usr/bin/python2
#-*-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", "aa", "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", "aa", "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_32607273/article/details/81569887