robot
最新文章(10)
Mqskit 和其它相關工具
CPython 的 GC 二、三事
寫 Mecurial Extension 是件快樂的事!
Mozilla 台灣辨公室徵人啟事
關於 Apple 的兩項專利
core dump 之前的 frame
怎麼發出 beep 聲?
先承認你要找的是奴才吧!
程式碼要清的多乾淨?
FreeBSD 的 Thread-Local Storage 實作
首頁
新編
最新留言
Entries RSS
重要關鍵字(10)
coding (122)
Python (93)
FreeBSD (71)
WEB (61)
URL (48)
hardware (46)
javascript (36)
Linux (34)
blog (30)
C++ (16)
所有關鍵字
新增 URL
Host SQL in Python II
by thinker
2 Columns
關鍵字:
Python
coding
這兩天改了一些東西,讓 Host SQL in $Python$ (好長,或許該取個正式的名稱了) 更完整。主要是支援 linkname:copy http://docs.python.org/lib/module-copy.html 這個 module 。 另外也產生 inert 和 update 的 SQL command。以下介紹目前的用法。 == Data Model == 這是定義 table 的方法: {{{ from pysql import table, int_f, str_f, date_f class users(table): uid = int_f() name = str_f() passwd = str_f() cdate = date_f() pass class posts(table): pid = int_f() uid = int_f() subject = str_f() body = str_f() pdate = date_f() pass }}} 定義完成的 table 可用以產生 schema {{{ >>> users_tb = users() >>> print users_tb.schema create table ( uid int, name text, passwd text, cdate date ); >>> }}} == Query == 簡單查詢 user 'abc': {{{ >>> from pysql import vview >>> vv = vview(users_tb) >>> vv.where(users_tb.name == 'abc') <pysql.vview object at 0x849268c> >>> str(vv) "select * from users A84b708c where (A84b708c.name = 'abc')" >>> }}} join users 和 posts 兩個 table,查詢 user 'abc' 所有的文章,並以時間排列: {{{ >>> posts_tb = posts() >>> vv = users_tb * posts_tb >>> vv.fields(posts_tb.subject, posts_tb.body, posts_tb.pdate) <pysql.vview object at 0x84b71ec> >>> vv.where((users_tb.uid == posts_tb.uid) & (users_tb.name == 'abc')) <pysql.vview object at 0x84b71ec> >>> vv.order(posts_tb.pdate) >>> str(vv) "select A84b724c.subject, A84b724c.body, A84b724c.pdate from users A84b708c, posts A84b724c where ((A84b708c.uid = A84b724c.uid) AND (A84b708c.name = 'abc'))" >>> }}} == Insert a new record == 新增一位使用者: {{{ >>> values = users_tb.factory(name='foo', passwd='1234', cdate='2006-11-3') >>> values.gen_insert_cmd() 'insert into users set passwd=%s, cdate=%s, name=%s' >>> }}} == Update records == 更改 user 'foo' 的 password: {{{ >>> values = users_tb.factory(passwd='5678') >>> values.gen_update_cmd(users_tb.name == 'foo') "update users set passwd=%s where (name = 'foo')" >>> }}} == 結語 == 目前這個工具雖然還缺完整,但可以看出發展性。比起 OR Mapping 精簡的多,也更有效率。OR Mapping 使許多原本在資料庫完成的運算,被轉移至 application 進行。另一方面,也使 DBMS 和 application 之間流量加大。效率和方便之間的是非,就由 programmer 自行判斷了,至少這裡提供了另一個選擇。 == 下載路徑 == * http://master.branda.to/downloads/pysql/pysql-20061103.tgz
最後更新時間: 2006-11-03 23:24:56 CST |
引用
查詢:
COMMENTS: