Python--双色球小程序

import time
import pymysql
import random


def operation_mysql(host, user, password, db, sql, port=3306, charset='uft8'):
"""操作mysql方法,根据sql入参判断做读操作还是增删改操作"""
conn = pymysql.connect(host=host, user=user, password=password, db=db,
port=port, charset=charset)
# 创建游标,指定游标类型为字典类型
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute(sql)
# 取sql前六个字符串,判断他是什么类型的sql语句
sql_start = sql[:6].upper()
if sql_start == 'SELECT':
res = cur.fetchall()
else:
conn.commit()
res = 'OK'
cur.close()
conn.close()
return res


def int_to_str(x):
"""将int转为字符串,如果是一位,前面加0"""
x = str(x)
if len(x) == 1:
x = '0{}'.format(x)
return x


def cur_time():
"""返回当前格式化的时间"""
return time.strftime('%Y-%m-%d %H:%M:%S')


def create_tickets(nums):
"""生成双色球的方法,num控制生成多少个双色球号码
“双色球”每注投注号码由6个红色球号码和1个蓝色球号码组成
红色球号码从1--33中选择;蓝色球号码从1--16中选择
结果红色球号码从小到大排序 + 蓝色球号码
每个号码逗号分隔,如果号码个数为1则需转为01"""
for i in range(nums):
red_nums = sorted(random.sample(range(1, 34), 6))
red_num = list(map(int_to_str, red_nums))
red_str = ','.join(red_num) # 红球的结果
blue_nums = random.sample(range(1, 17), 1)
blue_num = list(map(int_to_str, blue_nums))
blue_str = blue_num[0] # 篮球的结果
op_sql = 'insert into seq (red,blue,date) values ("%s","%s","%s");' % (red_str, blue_str, cur_time())
operation_mysql(
host='172.16.3.135',
user='root', password='123456',
port=3306, db='test', charset='utf8', sql=op_sql) # port这里一定要写int类型
print('已将全部双色球信息写入数据库!')


if __name__ == '__main__':
while True:
input_num = input('请输入想生成双色球的条数:')
if input_num.isdigit() and int(input_num) > 0:
num = int(input_num)
create_tickets(num)
break
else:
print('输入有误,请输入大于0的整数!')
posted @ 2018-01-24 15:14  王思磊  阅读(428)  评论(0编辑  收藏  举报