第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
。 。 。(一脸懵逼)
Python访问数据库:(廖雪峰python教程)
1. SQLite是一种轻量级的嵌入式数据库,其数据库就是一个文件。Python中内置SQLite3,无需另外安装。
要操作数据库,首先要连接到数据库,连接称作“Connection”。
连接数据库后,需要打开游标,称为“Cursor”,通过“Cursor”执行SQL语句,获得执行结果。
实践:
# 导入SQLite驱动:
>>> import sqlite3
# 连接到SQLite数据库
# 数据库文件是test.db
# 如果文件不存在,会自动在当前目录创建:
>>> conn = sqlite3.connect('test.db')
# 创建一个Cursor:
>>> cursor = conn.cursor()
# 执行一条SQL语句,创建user表:
>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
<sqlite3.Cursor object at 0x10f8aa260>
# 继续执行一条SQL语句,插入一条记录:
>>> cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')
<sqlite3.Cursor object at 0x10f8aa260>
# 通过rowcount获得插入的行数:
>>> cursor.rowcount
1
# 关闭Cursor:
>>> cursor.close()
# 提交事务:
>>> conn.commit()
# 关闭Connection:
>>> conn.close()
#---------------
#以下为查询记录操作
>>> conn = sqlite3.connect('test.db')
>>> cursor = conn.cursor()
# 执行查询语句:
>>> cursor.execute('select * from user where id=?', '')
<sqlite3.Cursor object at 0x10f8aa340>
# 获得查询结果集:
>>> values = cursor.fetchall()
>>> values
[('', 'Michael')]
>>> cursor.close()
>>> conn.close()
注意,最后一定要记得关闭之前打开的connection和cursor,否则会造成数据泄露。
官方文档:https://docs.python.org/2/library/sqlite3.html
照葫芦画瓢做这题。
code:
# coding = utf-8
__author__= 'liez' import random
import sqlite3 def make_number(num, length):
str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
a = []
i = 0
while i < num:
numstr = ''
for j in range(length):
numstr += random.choice(str)
if numstr not in a: #如果没重复
a.append(numstr)
i += 1
print(a)
return a def save(a):
try:
connect = sqlite3.connect('codelist.db')
except:
print("failed")
cur = connect.cursor()
cur.execute('create table if not exists codes(code char(20) primary key)')
for item in a:
cur.execute('insert into codes values (?)', [item])
print("success")
connect.commit()
cur.close()
connect.close() save(make_number(20, 10))
make_number()函数和0001题里的一样,save()函数有个地方卡了好久。
之前一直有一条错误:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 10 supplied.
搞了半天发现是这里:
for item in a:
cur.execute('insert into codes values (?)', [item]) #开始漏了‘[]’
(自己抠了半天才想起上*真是撒到家了 ̄へ ̄)
先前创建的table只能存放10个单个char的序列号,而序列号长度大于1就会出错。
加入生成长度为10的序列号,如果不加‘[]’,则每个序列号的10个char会被单独视作10个数据占十个格子(10 supplied)。
加上‘[]’表示这整个是一个元素。