使用 mysql-connector-python 操作 MySQL 資料庫

mysql-connector-python 是由 Oracle 提供的官方 Python 套件,用於與 MySQL 資料庫進行連線與操作。

安裝

pip install mysql-connector-python

基本連線與查詢範例

import mysql.connector

# 建立連線
conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="your_password",
    database="test"
)

cursor = conn.cursor()

# 執行查詢
cursor.execute("SELECT * FROM mytable")

# 取得結果
results = cursor.fetchall()
for row in results:
    print(row)

# 關閉連線
cursor.close()
conn.close()

建立資料表與新增資料

使用參數化查詢(防止 SQL Injection)

查詢與條件篩選

更新與刪除資料

取得資料筆數與逐筆讀取

錯誤處理範例


mysql-connector-python 適合用於資料存取、後端整合與自動化資料處理。也可搭配 pandas 使用 pd.read_sql() 整合分析流程。

Last updated