1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session,sessionmaker
db_connect = "mysql+pymysql://root:password@localhost:3306/db_name?charset=utf8"
create=create_engine(db_connect) SessionType=scoped_session(sessionmaker(bind=create,expire_on_commit=False))
def GetSession(): return SessionType()
from contextlib import contextmanager
@contextmanager def session_socpe(): session=GetSession() try: yield session session.commit() except: session.rollback() raise finally: session.close()
|
1 2
| with session_socpe() as session: obj = session.query(Model类).filter(Model类.字段==参数).first()
|
1 2 3
| with session_socpe() as session: obj = Model类(字段1=值1, 字段2=值2, 字段3=值3) session.add(obj)
|
1 2
| with session_socpe() as session: obj = session.query(Model类).filter(Model类.字段==参数).delete()
|
1 2
| with session_socpe() as session: obj = session.query(Model类).filter(Model类.字段==参数).update({"修改字段":"修改值"})
|
每次修改时,不用频繁地session.commit()
也方便了 万一出错后 的 rollback 回滚