生成优惠券,并将优惠券存入Mysql
2024-08-30 13:07:18
#coding:utf-8 import random
import string
import MySQLdb def gen_charint(filename, width =4, num=5): f = open(filename, 'wb')
charint = string.digits + string.letters
for i in range(num):
verify = [random.choice(charint) for j in range(width)]
verify = ''.join(verify) + '\n'
f.write(verify)
f.close() def store_mysql(filepath): conn = MySQLdb.connect(
host="localhost",
port=3306,
user='root',
passwd='root',
db='test',
charset='utf8'
) cursor = conn.cursor()
# 判断表是否存在
cursor.execute('show tables in test')
tables = cursor.fetchall()
findtables = False
for table in tables:
if 'coupon' in table:
findtables = True
# 下面的sql语句中的符号为反引号
# 由于刚开始设置code的字段长度偏小,报错后,调整这里的长度不起作用,查看数据库并未相应改变,需要手动更改数据库该字段长度
if not findtables:
cursor.execute('''
CREATE TABLE `coupon24`(
`id` INT NOT NULL AUTO_INCREMENT,
`coupon` VARCHAR(66) NOT NULL,
PRIMARY KEY(`id`));
''') f = open(filepath, 'rb')
for line in f.readlines():
code = line.split()
cursor.execute('insert into coupon24 (coupon) VALUES (%s)', code) conn.commit()
cursor.close()
conn.close() if __name__ == '__main__': filename = 'result24.txt'
width = 4
num = 11
gen_charint(filename, width, num)
store_mysql(filename)
注意点:
1、用列表生成式生成随机字数和数字,并通过join连接,并注意加上换行符
2、创建表时,表名和字段名均要用反引号,即TAB键上方的那个按键
最新文章
- BSA基础数据维护
- Web前端开发基础 第四课(颜色值)
- iOS实现(超级猜图)源码
- URAL 1242 Werewolf(DFS)
- 阿里云CentOS配置iptables防火墙[转]
- PHP专业开发IDE——Zend Studio 10.5预览版发布
- HDU1166 数状数组
- 学会WCF之试错法——安全配置报错分析
- Eureka注册客户端
- 不输入密码执行SUDO命令
- Python Iterables Iterators Generators
- Cognos命名空间不可用
- Redis 开启远程连接
- Hibernate主键生成策略及选择
- 20165234 预备作业3 Linux安装及学习
- mysql中trim()函数的用法
- 原生JavaScript支持6种方式获取元素
- 【原创 深度学习与TensorFlow 动手实践系列 - 1】第一课:深度学习总体介绍
- debug网页时小问题The source attachment does not contain the source for the file
- 前端 HTML form表单标签 select标签 option 下拉框
热门文章
- vim 不同的插入方式
- 【Nginx】解决Post请求变Get的问题
- Steps to Resolve the Database JAVAVM Component if it Becomes INVALID After Applying an OJVM Patch
- poj2282The Counting Problem(组合)
- 获取登陆信息 在created()方法中
- java中properties的使用实例
- CENTOS6.4上KVM虚拟机环境搭建
- 为sublime Text3 安装插件JS Format
- System类与两种输入流
- springboot设置接口超时