8.FastAPI_DB.md
last update: 2025-06-07
本章節說明如何使用 MySQL 建立資料庫與資料表,並透過 mysql-connector-python
搭配 FastAPI 進行資料新增與連線操作。
1. 建立資料庫與資料表(SQL 指令)
請在 MySQL Workbench 或終端機執行以下 SQL 指令:
CREATE DATABASE fastapi;
USE fastapi;
CREATE TABLE message (
id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
author VARCHAR(255) NOT NULL,
content VARCHAR(255) NOT NULL,
create_time DATETIME DEFAULT CURRENT_TIMESTAMP
);
SELECT * FROM message;
這會建立一個 message
表格,包含作者、內容與建立時間。
2. 安裝連線套件
pip install mysql-connector-python
3. 建立 FastAPI 與 MySQL 連線
from fastapi import FastAPI
from typing import Annotated
import mysql.connector
app = FastAPI()
# 建立資料庫連線
con = mysql.connector.connect(
user="root",
password="12345678", # your mysql password
host="localhost",
database="fastapi"
)
print("Database connected")
4. 新增資料 API
@app.get("/createMessage")
def createMessage(author: Annotated[str, None], content: Annotated[str, None]):
cursor = con.cursor()
cursor.execute("INSERT INTO message(author, content) VALUES(%s, %s)", [author, content])
con.commit()
return {"ok": True}
這個 API 可以透過網址查詢參數傳入內容,例如:
http://localhost:8000/createMessage?author=Tom&content=Hello
小結
項目
說明
建立資料庫與表格
使用 SQL 指令操作 MySQL
Python 套件
mysql-connector-python
資料庫連線
使用 mysql.connector.connect()
建立連線
插入資料
使用 cursor + execute + commit 寫入資料
這種方式適合用於快速實作或學習資料庫操作,後續也可擴充查詢、更新、刪除功能,或改為使用 ORM 管理資料結構。
Last updated