Read Sean

          Read me, read Sean.
          posts - 508, comments - 655, trackbacks - 9, articles - 4

          [Pylons] SQLAlchemy起步 - III. SQL Expression Language

          Posted on 2009-01-26 23:40 laogao 閱讀(1411) 評論(0)  編輯  收藏 所屬分類: On Python

          在介紹SQLAlchemy最核心最有價(jià)值的ORM部分之前,我們再簡單過一遍SQLAlchemy提供的SQL Expression Language用法,就從最基本的CRUD來舉例說明吧(接著上一篇的示例):

          ?1?from?sqlalchemy?import?select,update,delete
          ?2?
          ?3?conn?=?engine.connect()
          ?4?book_ins?=?book_table.insert(values=dict(title=u'Groovy?in?Action'))
          ?5?author_ins?=?author_table.insert(values=dict(name=u'Andrew?Glover'))
          ?6?conn.execute(book_ins)
          ?7?conn.execute(author_ins)
          ?8?book?=?conn.execute(select([book_table],?book_table.c.title.like(u'Groovy%'))).fetchone()
          ?9?author?=?conn.execute(select([author_table])).fetchone()
          10?bookauthor_ins?=?bookauthor_table.insert(values=dict(book_id=book[0],author_id=author[0]))
          11?conn.execute(bookauthor_ins)
          12?conn.execute(update(book_table,book_table.c.title==u'Groovy?in?Action'),?title=u'Groovy?in?Action?(中文版)')
          13?conn.execute(delete(bookauthor_table))
          14?conn.close()

          簡單說明一下代碼邏輯:
          首先從engine建立連接,然后做兩個(gè)insert動(dòng)作,分別insert一條book記錄(title為'Groovy in Action')和一條author記錄(name為'Andrew Glover'),這之后分別再做兩次select,得到剛insert的這兩條記錄,其中book記錄的select用到了過濾條件,相當(dāng)于"WHERE book.title like 'Groovy%'",然后構(gòu)建一條新的insert語句,用于insert一條bookauthor關(guān)系記錄,接下來,做一次update,將book.title為'Groovy in Action'的更新為'Groovy in Action (中文版)',最后,在關(guān)閉連接之前,做一次delete,刪除bookauthor中的記錄。

          在指定WHERE條件時(shí),.c是.columns的簡寫,所以book_table.c.title指代的就是book表的title列。更高級的用法是采用"&"、"|"、"!"三個(gè)符號,分別表示AND、OR和NOT,加上必要的"("和")"實(shí)現(xiàn)復(fù)雜的條件定義。由于傳遞給select()的第一個(gè)參數(shù)是個(gè)list,所以你應(yīng)該已經(jīng)猜到了,我們也可以多張表做關(guān)聯(lián)查詢。

          主站蜘蛛池模板: 新兴县| 惠来县| 襄垣县| 读书| 玉林市| 扎鲁特旗| 白水县| 文登市| 那曲县| 修武县| 灵石县| 广宁县| 宁强县| 宁河县| 肇源县| 鄢陵县| 普格县| 扶绥县| 德格县| 册亨县| 莲花县| 萝北县| 西盟| 华池县| 蕉岭县| 商都县| 澳门| 南汇区| 玉环县| 托克托县| 姚安县| 虎林市| 鄂州市| 巴马| 道孚县| 柞水县| 乐平市| 永仁县| 苗栗县| 泊头市| 屯留县|