Python

Python 使用 MySQL Connector 操作 MySQL/MariaDB 資料庫教學與範例

介紹如何使用 Python 的 MySQL Connector 模組連接 MySQL/MariaDB 資料庫,進行查詢、新增或刪除等各種操作。

Python 有許多 MySQL/MariaDB 資料庫相關的模組,而最常被使用的就是 MySQL Connector 與 MySQLdb 這兩個模組,以下是 MySQL Connector 模組的使用方式。

安裝 MySQL Connector 模組

開啟 Windows 中的命令提示自元,使用 pip 安裝 Python 的 MySQL Connector 模組:

pip install mysql-connector-python
安裝 Python 的 MySQL Connector 模組

安裝好之後,就可以開始使用了 Python 的 MySQL Connector 模組。

連接資料庫

以下是使用 MySQL Connector 模組連接資料庫的範例:

import mysql.connector
from mysql.connector import Error

try:
    # 連接 MySQL/MariaDB 資料庫
    connection = mysql.connector.connect(
        host='localhost',          # 主機名稱
        database='officeguide_db', # 資料庫名稱
        user='officeguide',        # 帳號
        password='your_password')  # 密碼

    if connection.is_connected():

        # 顯示資料庫版本
        db_Info = connection.get_server_info()
        print("資料庫版本:", db_Info)

        # 顯示目前使用的資料庫
        cursor = connection.cursor()
        cursor.execute("SELECT DATABASE();")
        record = cursor.fetchone()
        print("目前使用的資料庫:", record)

except Error as e:
    print("資料庫連接失敗:", e)

finally:
    if (connection.is_connected()):
        cursor.close()
        connection.close()
        print("資料庫連線已關閉")
資料庫版本: 5.5.5-10.4.8-MariaDB
目前使用的資料庫: ('officeguide_db',)
資料庫連線已關閉

查詢資料

以下是使用 SELECT 查詢資料的範例:

import mysql.connector
from mysql.connector import Error

try:
    # 連接 MySQL/MariaDB 資料庫
    connection = mysql.connector.connect(
        host='localhost',          # 主機名稱
        database='officeguide_db', # 資料庫名稱
        user='officeguide',        # 帳號
        password='your_password')  # 密碼

    # 查詢資料庫
    cursor = connection.cursor()
    cursor.execute("SELECT name, age FROM persons;")

    # 列出查詢的資料
    for (name, age) in cursor:
        print("Name: %s, Age: %d" % (name, age))


except Error as e:
    print("資料庫連接失敗:", e)

finally:
    if (connection.is_connected()):
        cursor.close()
        connection.close()
        print("資料庫連線已關閉")
Name: Arden, Age: 32
Name: Bond, Age: 54
Name: Cole, Age: 12
Name: Dana, Age: 19
資料庫連線已關閉

也可以使用 fetchall 將資料一次全部抓到 Python 中再處理:

import mysql.connector
from mysql.connector import Error

try:
    # 連接 MySQL/MariaDB 資料庫
    connection = mysql.connector.connect(
        host='localhost',          # 主機名稱
        database='officeguide_db', # 資料庫名稱
        user='officeguide',        # 帳號
        password='your_password')  # 密碼

    # 查詢資料庫
    cursor = connection.cursor()
    cursor.execute("SELECT name, age FROM persons;")

    # 取回全部的資料
    records = cursor.fetchall()
    print("資料筆數:", cursor.rowcount)

    # 列出查詢的資料
    for (name, age) in records:
        print("Name: %s, Age: %d" % (name, age))

except Error as e:
    print("資料庫連接失敗:", e)

finally:
    if (connection.is_connected()):
        cursor.close()
        connection.close()
        print("資料庫連線已關閉")
資料筆數: 4
Name: Arden, Age: 32
Name: Bond, Age: 54
Name: Cole, Age: 12
Name: Dana, Age: 19
資料庫連線已關閉

新增資料

以下是使用 INSERT 新增資料的範例:

import mysql.connector
from mysql.connector import Error

try:
    # 連接 MySQL/MariaDB 資料庫
    connection = mysql.connector.connect(
        host='localhost',          # 主機名稱
        database='officeguide_db', # 資料庫名稱
        user='officeguide',        # 帳號
        password='your_password')  # 密碼

    # 新增資料
    sql = "INSERT INTO persons (name, age, city) VALUES (%s, %s, %s);"
    new_data = ("Jack", 13, "Kaohsiung")
    cursor = connection.cursor()
    cursor.execute(sql, new_data)

    # 確認資料有存入資料庫
    connection.commit()

except Error as e:
    print("資料庫連接失敗:", e)

finally:
    if (connection.is_connected()):
        cursor.close()
        connection.close()

修改資料

以下是使用 UPDATE 更新資料的範例:

import mysql.connector
from mysql.connector import Error

try:
    # 連接 MySQL/MariaDB 資料庫
    connection = mysql.connector.connect(
        host='localhost',          # 主機名稱
        database='officeguide_db', # 資料庫名稱
        user='officeguide',        # 帳號
        password='your_password')  # 密碼

    # 更新資料
    sql = "UPDATE persons SET age = %s WHERE id = %s;"
    cursor = connection.cursor()
    cursor.execute(sql, (27, 6))

    # 確認資料有存入資料庫
    connection.commit()

except Error as e:
    print("資料庫連接失敗:", e)

finally:
    if (connection.is_connected()):
        cursor.close()
        connection.close()

刪除資料

以下是使用 DELETE 刪除資料的範例:

import mysql.connector
from mysql.connector import Error

try:
    # 連接 MySQL/MariaDB 資料庫
    connection = mysql.connector.connect(
        host='localhost',          # 主機名稱
        database='officeguide_db', # 資料庫名稱
        user='officeguide',        # 帳號
        password='your_password')  # 密碼

    # 更新資料
    sql = "DELETE FROM persons WHERE id = %s;"
    cursor = connection.cursor()
    cursor.execute(sql, (6,))

    # 確認資料有存入資料庫
    connection.commit()

except Error as e:
    print("資料庫連接失敗:", e)

finally:
    if (connection.is_connected()):
        cursor.close()
        connection.close()

參考資料:MySQL 官方文件pynative

Share
Published by
Office Guide

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago