Try   HackMD

MySQL 安裝及使用基本教學

MySQL安裝

資料來源:
https://www.learncodewithmike.com/2020/02/python-mysql.html
依步驟安裝MySQL
下載網站:https://www.mysql.com/downloads/

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

選擇Windows的安裝檔
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

下載MSI安裝檔
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

點擊Download按鈕後,在下一個畫面選擇「No thanks, just start my download.」即可
選擇Develop Default,開始進行安裝
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

過程中有一個步驟是需要設定MySQL資料庫的管理員密碼,如下圖:
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

設定完成後,在接下來的安裝步驟中,需要驗證密碼,如下圖:
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

安裝完成後,開啟MySQL的資料庫管理工具 MySQL Workbench,如下圖:
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

MySQL 使用

點擊local instance MySQL80

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

輸入下載時設定的密碼
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

建立資料庫
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

輸入資料庫名稱(kkbox)及選擇字元集為utf8,如下圖:
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

接著點選Apply,資料庫就建立完成。

建立資料表:
需在左邊側欄的地方,切換到Schemas(模式)頁籤,如下圖:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

其中可以看到剛剛所建立的資料庫,點選後,選擇Tables(資料表),右鍵新增資料表(Create Table),如下圖:
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

接著輸入資料表名稱(charts)及定義欄位,如下圖:
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

輸入完成後,同樣點選右下角的Apply,即完成資料表的建立。

新增資料表資料

MySQL資料庫的環境建置完成後,要透過Python進行存取,需要安裝pymysql套件(Package),可以利用 pip install pymysql 指令來達成。接著開啟Python專案,新增一個db.py檔,用來練習接下來的資料庫操作。

而Python專案要存取MySQL資料庫,除了引用pymysql模組(Module)外,還需要設定連線的參數,這邊利用Python字典(Dictionary)資料型態來進行設定,如下範例:

import pymysql
import charts
# 資料庫參數設定
db_settings = {
    "host": "127.0.0.1",
    "port": 3306,
    "user": "root",
    "password": "資料庫管理員密碼",
    "db": "kkbox",
    "charset": "utf8"
}

接著,將資料庫參數傳入pymysql模組(Module)的connect()方法(Method)中,建立Connection物件。另外,在連線的過程中,可能會發生例外錯誤,所以建議使用Python的try-except例外處理機制,如下範例:


import pymysql
import charts
# 資料庫設定
db_settings = {
    "host": "127.0.0.1",
    "port": 3306,
    "user": "root",
    "password": "資料庫管理員密碼",
    "db": "kkbox",
    "charset": "utf8"
}
try:
    # 建立Connection物件
    conn = pymysql.connect(**db_settings)
except Exception as ex:
    print(ex)

與資料庫的連線建立完成後,要進行相關的操作,需要建立Cursor(指標)物件來執行,這邊使用Python的with陳述式,當資料庫存取完成後,自動釋放連線,如下範例:

import pymysql
import charts
# 資料庫設定
db_settings = {
    "host": "127.0.0.1",
    "port": 3306,
    "user": "root",
    "password": "資料庫管理員密碼",
    "db": "kkbox",
    "charset": "utf8"
}
try:
    # 建立Connection物件
    conn = pymysql.connect(**db_settings)
    # 建立Cursor物件
    with conn.cursor() as cursor:
      #資料表相關操作
except Exception as ex:
    print(ex)

接著即可在with陳述式區塊中,撰寫與執行SQL語法,而新增資料至資料表中需執行INSERT的SQL語法,如下範例:

    # 建立Connection物件
    conn = pymysql.connect(**db_settings)
    # 建立Cursor物件
    with conn.cursor() as cursor:
        # 新增資料SQL語法
        command = "INSERT INTO charts(id, name, artist)VALUES(%s, %s, %s)"
        # 取得華語單曲日榜
        charts = charts.get_charts_tracks("H_PilcVhX-E8N0qr1-")
        for chart in charts:
            cursor.execute(
                command, (chart["id"], chart["name"], chart["album"]["artist"]["name"]))
        # 儲存變更
        conn.commit()

在第12行以華語單曲日榜的ID為例,呼叫get_charts_tracks()函式取得資料,回傳結果的格式為多筆字典(Dictionary)的串列(List),所以可以透過Python迴圈,利用Cursor(指標)物件執行新增資料的SQL語法,將每筆資料的id、歌曲名稱及歌手寫入資料庫中,最後透過Connection物件的commit()方法儲存。

開啟MySQL Workbench的檢視模式,即可看到執行結果,如下範例:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

執行結果:
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

查詢資料表資料

將華語單曲日榜的資料成功寫入charts資料表後,要透過Python撈取所有的資料,需執行SELECT的SQL語法,最後透過Cursor(指標)物件的fetchall()方法(Method)取回,如下範例


    # 建立Connection物件
    conn = pymysql.connect(**db_settings)
    # 建立Cursor物件
    with conn.cursor() as cursor:
        # 查詢資料SQL語法
        command = "SELECT * FROM charts"
        # 執行指令
        cursor.execute(command)
        # 取得所有資料
        result = cursor.fetchall()
        print(result)

如果只想取得單筆資料(第一筆),則可以利用fetchone()方法,如下範例:

    # 建立Connection物件
    conn = pymysql.connect(**db_settings)
    # 建立Cursor物件
    with conn.cursor() as cursor:
        # 新增資料指令
        command = "SELECT * FROM charts"
        # 執行指令
        cursor.execute(command)
        # 取得第一筆資料
        result = cursor.fetchone()
        print(result)

而要取得特定筆數的資料,可以透過fetchmany()方法,傳入所需的筆數,如下範例:

    # 建立Connection物件
    conn = pymysql.connect(**db_settings)
    # 建立Cursor物件
    with conn.cursor() as cursor:
        # 新增資料指令
        command = "SELECT * FROM charts"
        # 執行指令
        cursor.execute(command)
        # 取得前五筆資料
        result = cursor.fetchmany(5)
        print(result)

上述的查詢操作,皆是取回資料表中所有的資料,那要執行條件式的資料篩選,則可以加上WHERE語法,並且利用元組(Tuple)資料型態指定條件值,如下範例:

    # 建立Connection物件
    conn = pymysql.connect(**db_settings)
    # 建立Cursor物件
    with conn.cursor() as cursor:
        # 新增資料指令
        command = "SELECT * FROM charts WHERE name = %s"
        # 執行指令
        cursor.execute(command, ("太陽",))
        # 取得所有資料
        result = cursor.fetchall()
        print(result)

執行結果:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

修改資料表資料

假設要修改charts資料表中,id為5XeeDbHfELRucAOX6n的歌曲名稱(name)為Learn Code With Mike,需執行UPDATE的SQL語法,並且將主鍵(id)值及要修改的值(name)進行設定,最後透過Connection物件的commit()方法儲存。如下範例:

    # 建立Connection物件
    conn = pymysql.connect(**db_settings)
    # 建立Cursor物件
    with conn.cursor() as cursor:
        # 修改資料SQL語法
        command = "UPDATE charts SET name = %s WHERE id = %s"
        # 執行指令
        cursor.execute(command, ("Learn Code With Mike", "5XeeDbHfELRucAOX6n"))
      
        #儲存變更
        conn.commit()

刪除資料表資料

如果要刪除charts資料表中,id為-ovxsQyee7WVLKuikC的資料,需執行DELETE的SQL語法,並且設定主鍵(id)值,最後透過Connection物件的commit()方法儲存。


    # 建立Connection物件
    conn = pymysql.connect(**db_settings)
    # 建立Cursor物件
    with conn.cursor() as cursor:
        # 刪除特定資料指令
        command = "DELETE FROM charts WHERE id = %s"
        # 執行指令
        cursor.execute(command, ("-ovxsQyee7WVLKuikC",))
        #儲存變更
        conn.commit()