orm对象关系模型,将数据与程序对象建议一个映射关系,首推此框架
http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
#建立数据库引擎
from sqlalchemy import create_engine
create_engine包含有多个数据库连接配置等参数,并通过懒连接的方式建立连接
engine = create_engin(mysql://scott:tiger@hostname/dbname",encoding='latin1',echo=True)
# 创建会话
from sqlalchemy.orm import sessionmaker
or
from sqlalchemy.orm import create_session
#sessionmaker(bind=None)
#create_session(bind=None)
绑定的是db对象
以上两种方法都是创建的 sqlalchemy.orm.session.Session对象
session的正确用法
#介绍session相关的问题
#http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#what-does-the-session-do
# 非线程安全的
class ThingOne(object):
def go(self, session):
session.query(FooBar).update({"x": 5})
class ThingTwo(object):
def go(self, session):
session.query(Widget).update({"q": 18})
def run_my_program():
session = Session()
try:
ThingOne().go(session)
ThingTwo().go(session)
session.commit()
except:
session.rollback()
raise
finally:
session.close()
#close 关闭所有的transaction
创建对象实例 declare a mapping
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> from sqlalchemy import Column, Integer, String
>>> class User(Base):
... __tablename__ = 'users'
...
... id = Column(Integer, primary_key=True)
... name = Column(String)
... fullname = Column(String)
... password = Column(String)
...
... def __repr__(self):
... return "<User(name='%s', fullname='%s', password='%s')>" % (
... self.name, self.fullname, self.password)
增加
>>> ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
>>> session.add(ed_user)
>>> session.commit()
查询
>>> for instance in session.query(User).order_by(User.id):
... print(instance.name, instance.fullname)
ed Ed Jones
wendy Wendy Williams
mary Mary Contrary
fred Fred Flinstone
>>> for name, fullname in session.query(User.name, User.fullname):
... print(name, fullname)
ed Ed Jones
wendy Wendy Williams
mary Mary Contrary
fred Fred Flinstone
>>> for row in session.query(User, User.name).all():
... print(row.User, row.name)
<User(name='ed', fullname='Ed Jones', password='f8s7ccs')> ed
<User(name='wendy', fullname='Wendy Williams', password='foobar')> wendy
<User(name='mary', fullname='Mary Contrary', password='xxg527')> mary
<User(name='fred', fullname='Fred Flinstone', password='blah')> fred
修改
直接修改对象之后,commit即可
删除
session.delete(obj)