python练习册 每天一个小程序 第0002题

本文介绍如何将生成的优惠券或激活码批量保存至MySQL数据库的方法。通过Python操作MySQL,实现了从本地文件读取优惠码并将其插入指定数据库表的过程。
 1 #-*-coding:utf-8-*- 
 2 __author__ = 'Deen' 
 3 '''
 4 题目描述:
 5     将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
 6 '''
 7 """
 8 import MySQLdb as mdb
 9 
10 config = {
11     'host': '127.0.0.1',
12     'port': 3306,
13     'user': 'root',
14     'passwd': '',
15     'db': 'student',
16     'charset': 'utf8'
17 }
18 conn = mdb.connect(**config)
19 cursor = conn.cursor(cursorclass=mdb.cursors.DictCursor)
20 
21 
22 
23 cursor.execute('set names gbk')
24 
25 
26 
27 n=0
28 num=list()
29 
30 
31 for line in open("student12.txt"):
32     line=line.decode('gbk').encode('utf-8')
33 
34     n=n+1
35 
36     if n%6==1:
37         cursor.execute('insert into student12(sno) VALUES (%s)'%(line))
38 
39 """
40 
41 import MySQLdb as mdb
42 
43 config = {
44     'host': '127.0.0.1',
45     'port': 3306,
46     'user': 'root',
47     'passwd': '',
48     'db': 'ctf_test',
49     'charset': 'utf8'
50 }
51 conn = mdb.connect(**config)
52 cursor = conn.cursor(cursorclass=mdb.cursors.DictCursor)
53 cursor.execute('set names gbk')
54 
55 cursor.execute('create table codes(id int(5),code char(20))')
56 with open('poll_codes.txt','r') as fp:
57     for line in fp.readlines():
58         line = line.strip('\n').split(':')
59         cursor.execute('INSERT INTO codes VALUES (%s,%s)',line)
60 
61 
62 conn.commit()
63 cursor.close()
64 conn.close()

 

转载于:https://www.cnblogs.com/deen-/p/7135778.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值