defupdate_user(user_id:int,**kwargs)-> Optional[User]:with Session(engine)as session:
user = session.get(User, user_id)ifnot user:returnNone# 更新提供的字段for key, value in kwargs.items():ifhasattr(user, key):setattr(user, key, value)try:
session.add(user)
session.commit()
session.refresh(user)return user
except Exception as e:
session.rollback()raise e
# 使用示例
updated_user = update_user(1, email="newemail@example.com", is_active=False)
3.4 删除操作 (Delete)
defdelete_user(user_id:int)->bool:with Session(engine)as session:
user = session.get(User, user_id)ifnot user:returnFalsetry:
session.delete(user)
session.commit()returnTrueexcept Exception as e:
session.rollback()raise e
defbulk_create_users(users_data:list[dict])->list[User]:with Session(engine)as session:try:
users =[User(**data)for data in users_data]
session.add_all(users)
session.commit()for user in users:
session.refresh(user)return users
except Exception as e:
session.rollback()raise e
4.3 异步操作
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
# 异步数据库URL
ASYNC_DATABASE_URL ="postgresql+asyncpg://user:password@localhost/dbname"
async_engine = create_async_engine(ASYNC_DATABASE_URL)asyncdefasync_get_user(user_id:int)-> Optional[User]:asyncwith AsyncSession(async_engine)as session:
statement = select(User).where(User.id== user_id)
result =await session.exec(statement)return result.first()
from sqlalchemy.exc import IntegrityError, OperationalError
defsafe_create_user(username:str, email:str)->tuple[Optional[User],str]:try:
user = create_user(username, email)return user,"Success"except IntegrityError:returnNone,"User with this email already exists"except OperationalError:returnNone,"Database connection error"except Exception as e:returnNone,f"Unexpected error: {str(e)}"
5.3 模型验证
from pydantic import EmailStr, validator
classUserCreate(SQLModel):
username:str
email: EmailStr
@validator('username')defusername_must_be_valid(cls, v):iflen(v)<3:raise ValueError('Username must be at least 3 characters long')return v
要查询 MySQL 默认的存储引擎,可以使用以下 SQL 查询语句:
SELECT default_storage_engine;解释:
SELECT: 表示你要执行一个查询。default_storage_engine: 这是一个 MySQL 系统变量,它存储着当前 MySQL 服务器的默认存储引擎。…