sqlalchemy同步跟新
时间: 2023-12-15 11:06:32 浏览: 77
SQLAlchemy提供了两种同步更新数据库的方式:
1. 自动提交方式:在每次对数据库进行修改后自动提交事务并同步更新数据库。
```python
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
age = Column(Integer)
engine = create_engine('mysql+pymysql://user:password@host:port/database')
Session = sessionmaker(bind=engine)
session = Session()
user = User(name='John', age=30)
session.add(user)
session.commit() # 自动提交事务并同步更新数据库
```
2. 手动提交方式:在对数据库进行修改后手动提交事务并同步更新数据库。
```python
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
age = Column(Integer)
engine = create_engine('mysql+pymysql://user:password@host:port/database')
Session = sessionmaker(bind=engine)
session = Session()
user = User(name='John', age=30)
session.add(user)
session.flush() # 把修改的内容同步到数据库
session.commit() # 手动提交事务
```
阅读全文