mysql orm

参考文章https://www.cnblogs.com/franknihao/p/7268752.html

    https://www.cnblogs.com/sss4/p/9771916.html

 

step1: 获取连接

>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///:memory:', echo=True)

step2:获取基类
>>> from sqlalchemy.ext.declarative import declarative_base

>>> Base = declarative_base()

step3:创建类继承基类:
>>> from sqlalchemy import Column, Integer, String
>>> class User(Base):
...     __tablename__ = 'users'
...
...     id = Column(Integer, primary_key=True)
...     name = Column(String)
...     fullname = Column(String)
...     nickname = Column(String)
...
...     def __repr__(self):
...        return "<User(name='%s', fullname='%s', nickname='%s')>" % (
...                             self.name, self.fullname, self.nickname)

step4:生成数据表:
>>> Base.metadata.create_all(engine)

step5:创建数据实例通过session操作数据库表
创建session:
>>> from sqlalchemy.orm import sessionmaker
>>> Session = sessionmaker(bind=engine)

数据实例化:
>>> ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname')

提交数据:
>>> session.add(ed_user)
确认提交:
>>> session.commit()
最后关闭连接:
>>> session.close()
 
 
 查询数据:
def get_one(self):
  return self.session.query(News).get(1) '''News是基于Base基类创建的数据类'''
def get_more(self):
  retirm self.session.query(News).filter_by(is_valid=1)
上述代码的基础是:
def __init__(self):
  self.session = Session()

数据获取后的判断:
  obj = OrmTest()
  rest = obj.get_one()
  if rest:
    print('Id:{0}=>{1}'.formate(rest.id,rest.title))
  else:
    print('not exist')
 
 
posted @ 2019-06-14 15:05  braveheart007  阅读(116)  评论(0编辑  收藏  举报