这完全没任何提示就失败了是为什么?
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, URL
from sys_user import SysUser
# 创建数据库连接
engine = create_engine(URL.create("mysql+pymysql", **{
"host": "...",
"port": 3306,
"username": "root",
"password": "...",
"database": "...",
}), echo=True)
# 创建 sessionmaker 对象
Session = sessionmaker(bind=engine,autocommit=False)
# 创建 session
session = Session()
# 创建对象
obj = SysUser(account="cc") # 根据你的模型类进行替换
# 将对象添加到 session
success = session.add(obj)
# 判断是否插入成功
if success:
# 提交事务
session.commit()
print("Object inserted successfully.")
else:
print("Failed to insert object.")
- 模型
from sqlalchemy import String, DateTime, Integer
from sqlalchemy.orm import Mapped, mapped_column
import datetime
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
class SysUser(Base):
__tablename__ = 'table_aaa'
id: Mapped[int] = mapped_column(primary_key=True)
account: Mapped[str] = mapped_column(String(100))
- 实际情况:压根连 add 方法都没触发:(删除了部分非必要代码)
- 调试情况:
问题是为什么一定要赋值之后才能生效呢?方法不是已经返回了对象么?
解决方案找打了,令人窒息:必须要用
with