2025年3月6日 星期四

Python 18 小時入門--第 15 小時:Python 與資料庫(Database Management)

 📌 第 15 小時:Python 與資料庫(Database Management)

Python 可用於資料庫管理,讓我們能夠儲存、查詢、更新和刪除大量數據。本章將介紹:

  1. SQL vs NoSQL 資料庫
  2. 使用 sqlite3 操作 SQLite
  3. 使用 MySQL 進行資料管理
  4. 使用 MongoDB 儲存 NoSQL 資料
  5. SQLAlchemy 進行 ORM(物件關聯映射)

🔹 1. SQL vs NoSQL 資料庫

類型 說明 例子
SQL(關聯式資料庫) 結構化數據,使用表格儲存 MySQL, PostgreSQL, SQLite
NoSQL(非關聯式資料庫) 適用於非結構化數據(JSON、文件) MongoDB, Firebase, Redis

📌 SQL 適合結構化數據(如使用者資料),NoSQL 適合非結構化數據(如聊天記錄)。


🔹 2. 使用 sqlite3 操作 SQLite

SQLite 是輕量級的 SQL 資料庫,適合小型應用程式,內建於 Python 無需額外安裝。

🟢 建立 SQLite 資料庫

import sqlite3

# 連接 SQLite(若檔案不存在會自動建立)
conn = sqlite3.connect("example.db")
cursor = conn.cursor()

# 建立表格
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        age INTEGER
    )
''')

conn.commit()
conn.close()

🟢 插入數據

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 25))
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Bob", 30))

conn.commit()
conn.close()

🟢 查詢數據

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()

for row in rows:
    print(row)

conn.close()

📌 結果

(1, 'Alice', 25)
(2, 'Bob', 30)

🟢 更新與刪除數據

cursor.execute("UPDATE users SET age = ? WHERE name = ?", (26, "Alice"))
cursor.execute("DELETE FROM users WHERE name = ?", ("Bob",))

🔹 3. 使用 MySQL 操作大型資料庫

MySQL 是常見的關聯式資料庫,適合中大型應用,如 網站後端、電子商務系統

🟢 安裝 MySQL Connector

pip install mysql-connector-python

🟢 連接 MySQL

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="你的密碼",
    database="test_db"
)
cursor = conn.cursor()

🟢 創建 MySQL 資料表

cursor.execute('''
    CREATE TABLE users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100),
        age INT
    )
''')

🟢 插入數據

cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ("Charlie", 28))
conn.commit()

🟢 查詢數據

cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)

🔹 4. 使用 MongoDB(NoSQL 資料庫)

MongoDB 是 NoSQL 資料庫,適合 儲存 JSON 格式的大量數據

🟢 安裝 pymongo

pip install pymongo

🟢 連接 MongoDB

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["users"]

🟢 插入 JSON 數據

user = {"name": "Alice", "age": 25}
collection.insert_one(user)

🟢 查詢數據

for user in collection.find():
    print(user)

🔹 5. SQLAlchemy 進行 ORM

SQLAlchemy 是 ORM(物件關聯映射),允許我們用 Python 類別操作資料庫。

🟢 安裝 SQLAlchemy

pip install sqlalchemy

🟢 定義模型

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(100))
    age = Column(Integer)

# 建立資料庫連線
engine = create_engine("sqlite:///example.db")
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

🟢 插入數據

user = User(name="Alice", age=25)
session.add(user)
session.commit()

🟢 查詢數據

users = session.query(User).all()
for user in users:
    print(user.name, user.age)

📌 第 15 小時小結

SQL(如 MySQL、SQLite)適合結構化數據,NoSQL(如 MongoDB)適合非結構化數據
使用 sqlite3 操作 SQLite,小型應用適用
使用 MySQL 處理大量結構化數據
使用 MongoDB 儲存 JSON 格式的 NoSQL 數據
使用 SQLAlchemy 進行 ORM,讓 Python 直接操作資料庫

學完這一章,你已掌握 Python 與資料庫整合,下一步將學習 Python 部署與雲端應用,讓你的程式真正上線!🚀

沒有留言:

張貼留言