SQLalchemy使用補充

  1.engine = create_engine(echo=true)sql

     sqlalchemy與數據庫通訊的命令都將打印出來數據庫

 1 2018-01-13 09:42:43,634 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8' and `Collation` = 'utf8_bin'
 2 2018-01-13 09:42:43,634 INFO sqlalchemy.engine.base.Engine {}
 3 2018-01-13 09:42:43,738 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
 4 2018-01-13 09:42:43,739 INFO sqlalchemy.engine.base.Engine {}
 5 2018-01-13 09:42:43,754 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
 6 2018-01-13 09:42:43,754 INFO sqlalchemy.engine.base.Engine {}
 7 2018-01-13 09:42:43,756 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin AS anon_1
 8 2018-01-13 09:42:43,757 INFO sqlalchemy.engine.base.Engine {}
 9 2018-01-13 09:42:43,790 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
10 2018-01-13 09:42:43,792 INFO sqlalchemy.engine.base.Engine UPDATE users SET name=(concat(users.name, %(name_1)s)) WHERE users.id > %(id_1)s
11 2018-01-13 09:42:43,792 INFO sqlalchemy.engine.base.Engine {'name_1': '512', 'id_1': 0}
View Code

  2.聲明一個映射(declare a Mapping)session

  declarative_base類維持了一個從類到表的關係,一般一個應用使用一個base實例,全部實體類都應該繼承此類對象app

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

  3.建立Sessionide

  Session是真正與數據庫通訊的handler,你還能夠把他理解一個容器,add就是往容器中添加對象函數

 1 from sqlalchemy.orm import sessionmaker
 2 Session = sessionmaker(bind=engine)
 3 
 4 #建立完session就能夠添加數據了  
 5 ed_user = User('ed','Ed jone','edpasswd')
 6 session.add(ed_user)
 7 
 8 #也可使用session.add_all()添加多個對象 
 9 #session.add_all([user1,user2,user3])
10 
11 print ed_user in session  # True
12 session.rollback()
13 print ed_user in session # False
View Code

  執行完add方法後,ed_user對象處於pending狀態,不會觸發INSERT語句,固然ed_uesr.id也爲None,若是在add方後有查詢(session.query),那麼會flush一下,把數據刷一遍,把全部的pending信息先flush再執行query。spa

  4.對象實例有四種狀態  code

  Transient(瞬時的):這個狀態的對象還不在session中,也不會保存到數據庫中,主鍵爲None(不是絕對的,若是Persistent對象rollback後雖然主鍵id有值,但仍是Transient狀態的)。orm

  Pending(掛起的):調用session.add()後,Transient對象就會變成Pending,這個時候它仍是不會保存到數據庫中,只有等到觸發了flush動做纔會存在數據庫,好比query操做就能夠出發flush。一樣這個時候的實例的主鍵同樣爲None對象

  Persistent(持久的):session中,數據庫中都有對應的一條記錄存在,主鍵有值了。

  Detached(遊離的):數據庫中有記錄,可是session中不存在,對這個狀態的對象進行操做時,不會觸發任何SQL語句。

  5.經常使用過濾操做

 1 equals:
 2         query.filter(User.name == 'ed')
 3 
 4 not equal:
 5        query.filter(User.name !='ed') 
 6 
 7 LIKE:
 8         query.filter(User.name.like('%d%')
 9 
10 IN:
11         query.filter(User.name.in_(['a','b','c'])
12 
13 NOT IN:
14        query.filter(~User.name.in_(['ed','x'])
15 
16 IS NULL:
17        filter(User.name==None)
18 
19 AND:
20      from sqlalchemy import and_
21      filter(and_(User.name == 'ed',User.fullname=='xxx')) 
22 
23 或者屢次調用filter或filter_by:
24      filter(User.name =='ed').filter(User.fullname=='xx')
25 
26 OR:
27      from sqlalchemy import or_
28   query.filter(or_(User.name == ‘young’, User.name == ‘sun’))
View Code

  6.查詢返回結果

1 query.all(),all()返回列表
2 query.first():返回第一個元素
3 query.one()有且只有一個元素時才正確返回。
4 
5 filter函數還能夠接收text對象,text是SQL查詢語句的字面對象,好比:
6 
7 for user in session.query(User).filter(text(「id<20」)).order_by(text(「id」)).all():
8     print user.name
View Code

  7.兩種count

1 第一種是純粹是執行SQL語句後返回有多少行,對應的函數count(),第二個是func.count(),適用在分組統計,好比按性別分組時,男的有多少,女的多少:
2 
3 session.query(User).filter(User.name==’sun’).count()
4 session.query(func.count(), User.gender).group_by(User.gender).all( )
View Code

  8.關聯查詢

  primaryjoin:用在一對多或者多對一的關係中,默認狀況鏈接條件就是主鍵與另外一端的外鍵,用primaryjoin參數能夠用來指定鏈接條件 ,好比:下面user的address必須現address是一'tony'開頭:

 1  class User(Base):
 2       __tablename__ = 'user'
 3       id = Column(Integer, primary_key=True)
 4       name = Column(String)
 5   
 6       addresses = relationship("Address",
 7                       primaryjoin="and_(User.id==Address.user_id, "
 8                           "Address.email.startswith('tony'))",
 9                       backref="user")
10   
11   class Address(Base):
12       __tablename__ = 'address'
13       id = Column(Integer, primary_key=True)
14       email = Column(String)
15       user_id = Column(Integer, ForeignKey('user.id'))
View Code
相關文章
相關標籤/搜索