要使用FastAPI来对MySQL数据库进行增删改查,需要添加相应的库和依赖项。以下是需要执行的步骤:
- 安装依赖项:
pip3 install fastapi
pip3 install uvicorn
pip3 install mysql-connector-python
- 在代码中引入mysql-connector和FastAPI:
import mysql.connector
from fastapi import FastAPI
- 创建MySQL连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
- 创建FastAPI应用程序实例
app = FastAPI()
- 在FastAPI中定义API路由
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/users/{user_id}")
async def read_user(user_id: int):
mycursor = mydb.cursor()
sql = "SELECT * FROM users WHERE id = %s"
val = (user_id,)
mycursor.execute(sql, val)
result = mycursor.fetchone()
return {"user_id": result[0], "name": result[1], "email": result[2]}
@app.post("/users")
async def create_user(name: str, email: str):
mycursor = mydb.cursor()
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
val = (name, email)
mycursor.execute(sql, val)
mydb.commit()
return {"name": name, "email": email, "id": mycursor.lastrowid}
@app.put("/users/{user_id}")
async def update_user(user_id: int, name: str = None, email: str = None):
mycursor = mydb.cursor()
sql = "UPDATE users SET name = %s, email = %s WHERE id = %s"
val = (name, email, user_id)
mycursor.execute(sql, val)
mydb.commit()
return {"message": "user updated successfully!"}
@app.delete("/users/{user_id}")
async def delete_user(user_id: int):
mycursor = mydb.cursor()
sql = "DELETE FROM users WHERE id = %s"
val = (user_id,)
mycursor.execute(sql, val)
mydb.commit()
return {"message": "user deleted successfully!"}
在上面的代码中,我们定义了4个路由:
- GET /: 根路由
- GET /users/{user_id}: 根据用户ID获取用户信息
- POST /users: 创建新用户
- PUT /users/{user_id}: 根据用户ID更新用户信息
- DELETE /users/{user_id}: 根据用户ID删除用户
这样,我们就成功地使用FastAPI对MySQL进行增删改查操作。