sqlite3 on python for newbies

python 集成了 sqlite3 ,其接口很简单:

import sqlite3

db_connection = sqlite3.connect(db_filename)

db_cursor = db_connection.cursor()

db_cursor.execute('select * from tt')

result_one = db_cursor.fetchone()

result_all = db_cursor.fetchall()

在sqlite 中 有一张 sqlite_master 的表,里边存储的是所有表的建表信息,所以可以通过以下语句查询所有表:

select name from sqlite_master where TYPE = "table"

sqlite 中的 db_cursor.description 是对各列的描述信息:

columnnames = map(lambda x:x[0], db_cursor.description)

sqlite 允许设置数据库读取记录的方法,如下方法可以将结果改为 dict :

db_connection.row_factory = lambda curf, rowf:dict(zip(map(lambda x:x[0], curf.description), rowf))

posted on 2014-07-02 11:19  很遗憾我不是  阅读(230)  评论(0编辑  收藏  举报