当前位置:Linux教程 - Linux - 让 Python 与 DB 共舞 - 谈 DB-API 模组

让 Python 与 DB 共舞 - 谈 DB-API 模组

使用 Python 的同好们应该知道 python 有许多不同的 module,光 mysql 的 module 就有三四个以上。 每个使用的介面都不太相同。这问题常会困扰著初学者,不知道要学那一样。大家没注意过 Python SIGs(Special Interest Groups)有一个 group 称为 db-sig,由对 python database部分有兴趣的朋友组成。他们定义了一组称为 DB-API 的介面,现在已经推出2.0 版了。我并不是说这个 API 会有多好,不过它定出一个各 database module可以依循的介面,让 Python 的爱用者不需要再为学习或使用那一个 module 好而烦恼。(我最怕用了某个没人维护的 module,那将来该怎么辨? 重写?)

闲话少说,我要介绍的就是 DB-API。目前我所使用的 DB 为 PostgreSQL 7,目常最新的版本。使用的 module 为 PyGreSQL-3.0,tarball 有些问题的版本,小修一下,似乎没什么问题。目前 FreeBSD 的 ports 只做到 2.4 版,3.0 版的ports 我随手做了一下,拿 2.4 的来小改。
ftp://www.branda.to/pub/py-PyGreSQL3.tar.gz

关于 Linux 部分,请使用 tarball 自行处理。

以 PyGreSQL-3.0 为例,DB-API 使用如下:


1 import pgdb
2
3 conn = pgdb.connect=(host=''xxxx'', database=''template1'', user=''xxx'', passwor
4 cursor = conn.cursor()
5 qstr = ''select * from pg_table;''
6 cursor.execute(qstr)
7 print ''row #.=>'', cursor.rowcount
8 print ''one row =>'', cursor.fetch()
9 print ''three row =>'', cursor.fetchmany(3)
10 print ''all row =>'', cursor.fetchall()
11 cursor.close()
12 conn.close()
--------------------
row #.=> 28
one row => [''pg_type'', ''pgsql'', ''t'', ''f'', ''f'']
three row => [[''pg_type'', ''pgsql'', ''t'', ''f'', ''f''], [''pg_attribute'', ''pgsql'', ''t, ''f'', ''f''], [''pg_proc'', ''pgsql'', ''t'', ''f'', ''f'']]
all row => [[''pg_type'', ''pgsql'', ''t'', ''f'', ''f''], [''pg_attribute'', ''pgsql'', ''t'',''f'', ''f''], [''pg_proc'', ''pgsql'', ''t'', ''f'', ''f''], [''pg_class'', ''pgsql'', ''t'',

...... skip ............

[''pg_ipl'', ''pgsql'', ''f'', ''f'', ''f''], [''pg_inheritproc'', ''pgsql'', ''f'', ''f'',''f'']]



行 1,先 import pgdb。这个基本知识就不用多说了。

行 3,先建设一个 database connection,database 参数为 database 名称。

行 4,产生一个 cursor object,cursor 为实际接受 SQL command 的 object,的执行结果。

行 6,使用刚才产生的 cursor object 执行 SQL command ''select * from pg_tables;'',pg_table 为 PostgreSQL 的 system table,你可下任何其它的 SQL command。

行 7,则显示 SQL command 所产生的资料的 row 数目,为 28 rows。

行 8,展示 fetchone() 这个 method 的功能,fetchone 会读取执行结果的第一个 row。

行 9,展示 fetchmany(),这个 method 可以读取执行结果的头 n 个 row。

行 10,fetchall() 读回所有的结果。

从上例我们可以看到 DB-API 的介面定义的很简单,fetchxxx() 所取得的结为list of list,除了 fetchone() 为单一个 list。除了上面所展示的功能之外,DB-API 还包含了 transation 的介面,commit(),rollback()。commit() 为cursor 的 method,会将这次 commit 之前,前次 commit 之后的所有 SQLcommand 进行 commit。而 rollback() 也是 cursor 的 method,用来 aborttransation,使 database 回到本次 transation 执行之前的状况。关于transation 我就不多做说明了。