PythonShowMeTheCode(0002): 連接數(shù)據(jù)庫

1. 題目

第 0002 題:將 0001 題生成的 200 個(gè)激活碼(或者優(yōu)惠券)保存到 MySQL關(guān)系型數(shù)據(jù)庫中。

2.實(shí)現(xiàn)

step 1:安裝MySQL(按解壓免安裝版本介紹)

step 2:運(yùn)行MySQL

#cmd進(jìn)入MySQL解壓bin目錄
cd %解壓文件bin目錄%

#安裝MySQL服務(wù),啟動服務(wù)
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:編程實(shí)現(xiàn)

# -*- 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出現(xiàn)error: Unable to find vcvarsall.bat</i>

  • 安裝wheel
pip install wheel
  • 這里下載庫所對應(yīng)的.whl文件,善用Ctrl+F
下載頁面
  • 根據(jù)python版本下載對應(yīng)的文件,例如python35下載包含cp35的即可
  • 進(jìn)入XX.whl文件所在的文件夾,執(zhí)行pip install XX.whl

<i>II. 向數(shù)據(jù)庫寫入中文時(shí)出現(xiàn)亂碼</i>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容