2017年11月20日

Python 练习册 => 0002 将 0001 题生成的 200 个激活码保存到 MySQL 关系型数据库中

心得

  • 使用 pymysql 模块操作 MySQL 数据库。(感觉比 MySQLDB 好用些,Python3 安装 MySQLDB 各种报错)
  • pymysql 使用范例
  • sql 语句很基础,很重要

代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pymysql.cursors
import uuid


def main():
    conn = pymysql.connect(host='localhost',
                         user='root',
                         passwd='root',
                         db='show_me_the_code',
                         charset='utf8',
                         cursorclass=pymysql.cursors.DictCursor)

    try:
        with conn.cursor() as cursor:
            init_table(cursor)
            sql = "INSERT INTO `ActivationCode` (`code`) VALUES (%s)"
            code_list = get_activation_code_list()
            for code in code_list:
                print(code)
                cursor.execute(sql, (code,))
        conn.commit()
    finally:
        conn.close()


def init_table(cursor):
    # 如果数据表已经存在使用 execute() 方法删除表。
    cursor.execute("DROP TABLE IF EXISTS ActivationCode")
    # 创建数据表SQL语句
    sql = """CREATE TABLE ActivationCode (
                `id` INT NOT NULL AUTO_INCREMENT,
                `code` VARCHAR(50) NOT NULL,
                PRIMARY KEY(`id`)
                )
            """
    cursor.execute(sql)


def get_activation_code_list():
    result = []
    for i in range(200):
        result.append(str(uuid.uuid4()))
    return result


if __name__ == "__main__":
    main()

“以书为舟,遨游尘世”,
最好的免费 kindle 电子书分享站:

You may also like...

发表回复

您的电子邮箱地址不会被公开。


*