1. 題目
第 0002 題:將 0001 題生成的 200 個激活碼(或者優惠券)保存到 MySQL關系型數據庫中。
2.實現
step 1:安裝MySQL(按解壓免安裝版本介紹)
step 2:運行MySQL
#cmd進入MySQL解壓bin目錄
cd %解壓文件bin目錄%
#安裝MySQL服務,啟動服務
mysqld -nt -install
net start mysql
#登陸
mysql -u root -p
Enter your password:
Welcome to the MySQL monitor...
step 3:安裝mysqlclient庫
pip install mysqlclient
step 4:編程實現
# -*- coding:utf-8 -*-
import uuid
import MySQLdb
def create_code(num, length):
result = []
for i in range(0, num):
code_str = str(uuid.uuid4()).replace('-', '')[:length].upper()
for j in range(4, length, 5):
code_str = code_str[:j] + '-' + code_str[j:]
if code_str not in result:
result.append(code_str)
return result
def save_code(code_result):
if len(code_result) == 0:
return
db = MySQLdb.connect(user="root", passwd="", db="code")
cursor = db.cursor()
cursor.execute("show tables in `code`")
tables = cursor.fetchall()
if ('code',) in tables:
print("Create table 'code' already.")
else:
cursor.execute("create table code(id int auto_increment primary key, code varchar(20));")
for i in range(len(code_result)):
cursor.execute("insert into code(code) values(%s);", (code_result[i],))
cursor.close()
db.commit()
db.close()
if __name__ == '__main__':
save_code(create_code(20, 16))
3. 解決問題
<i>I. 安裝mysqlclient出現error: Unable to find vcvarsall.bat</i>
- 安裝wheel
pip install wheel
- 在這里下載庫所對應的.whl文件,善用Ctrl+F
下載頁面
- 根據python版本下載對應的文件,例如python35下載包含cp35的即可
- 進入XX.whl文件所在的文件夾,執行
pip install XX.whl
<i>II. 向數據庫寫入中文時出現亂碼</i>