python 练习0001、0002

版权声明:喜欢就点个赞吧,有啥疑问可以留言交流~ https://blog.csdn.net/m0_38015368/article/details/89183786

题目一

做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?

代码

# 0001.py
import random 
import string

def get_random(n):
    field = string.digits + string.ascii_letters
    return ''.join(random.sample(field, n))

def concatenate(n):
    return '-'.join([get_random(4) for i in range(n)])

def generate(n):
    return [concatenate(4) for i in range(n)]

if __name__ == '__main__':
    codes = generate(10)
    print(codes)

参考: Python Show-Me-the-Code 第 0001 题 生成激活码

题目二

将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。

代码

from 0001 import generate

import pymysql

def connect():
    # 本地 用户名 用户密码 数据库名
    return pymysql.connect('localhost', 'zzz', '123', 'zzz')

def create_table(db, table_name):
    # 创建游标
    cursor = db.cursor()
    # 执行SQL 
    sql = 'DROP TABLE IF EXISTS ' + table_name
    cursor.execute(sql)
    # 创建表
    sql = 'CREATE TABLE ' + table_name + ' (code CHAR(20) NOT NULL)'
    cursor.execute(sql)
    # 关闭游标
    cursor.close()

def insert_table(db, codes):
    cursor = db.cursor()
    # 将每一个码转换为元组形式
    # codes = [(code) for code in codes]
    sql = 'INSERT INTO codes (code) VALUES (%s)'
    try:
        # 执行 sql
        cursor.executemany(sql, codes)
        # 提交到数据库执行
        db.commit()
    except:
        # 错误则回滚
        db.rollback()
    cursor.close()

def select_table(db):
    cursor = db.cursor()
    sql = 'select * from codes'
    try:
        cursor.execute(sql)
        # results 是元组对象
        results = cursor.fetchall()
        for line in results:
            for row in line:
                print(row, end='\t')
            print()
    except:
        print('Error')
    cursor.close


if __name__ == '__main__':
    db = connect()
    create_table(db, 'codes')
    codes = generate(100)
    insert_table(db, codes)
    select_table(db)
    # 关闭
    db.close()

pymysql 需要单独安装 pip3 install pymysql

排错

连接数据库是可能会出现两个错误:

  • pymysql.err.InternalError: (1698, “Access denied for user ‘root’@‘localhost’”)
  • pymysql.err.OperationalError: (1044, “Access denied for user ‘zzz’@‘localhost’ to database ‘zzz’”)

解决方案:

  1. 不要使用 root 用户登录,要创建新的用户
  2. 要赋予新用户足够的权限

创建新用户的命令:

mysql> USE mysql;
mysql> CREATE USER 'YOUR_SYSTEM_USER'@'localhost' IDENTIFIED BY '';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'YOUR_SYSTEM_USER'@'localhost';
mysql> UPDATE user SET plugin='auth_socket' WHERE User='YOUR_SYSTEM_USER';
mysql> FLUSH PRIVILEGES;
mysql> exit;

$ systemclt restart mysql.service

参考: ERROR 1698 (28000): Access denied for user ‘root’@‘localhost’

猜你喜欢

转载自blog.csdn.net/m0_38015368/article/details/89183786