====== Python SQLite 编程 ====== SQLite 是个轻量级的数据库系统,无需系统服务,只有一个db文件,可移植性很好。\\ 如果有大量数据需要处理的话是个很好的选择。 ===== SQLite 安装===== Windows下使用Python2.5版本可以直接使用。\\ 在Linux下面需要先装sqlite再装Python否则会出现“No module named _sqlite3”的错误: >>> import sqlite3 Traceback (most recent call last): File "", line 1, in File "/linux/depot/Python-2.5/lib/python2.5/sqlite3/__init__.py", line 24, in from dbapi2 import * File "/linux/depot/Python-2.5/lib/python2.5/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ImportError: No module named _sqlite3 >>> 这是由于 Python 自带的sqlite3模块只是sqlite的一个接口,包含实现部分。 ==== 安装SQLite ==== 下载SQLite的最新版本:http://www.sqlite.org/ curl http://www.sqlite.org/sqlite-amalgamation-3.5.6.tar.gz -o sqlite-amalgamation-3.5.6.tar.gz tar -xzvf sqlite-amalgamation-3.5.6.tar.gz cd sqlite-3.5.6 ./configure --prefix=/you/lib/location/here make make install ==== 安装 Python ==== cd cd Python-2.5.1 ./configure --prefix=/you/lib/location/here make make install 这样就可以用了。 ===== Python 下面使用 Sqlite3 ===== 通过sqlite3模块能够很容易的操作数据库。 ==== 实例 ==== #!/depot/Python-2.5/bin/python import sqlite3 #链接数据库文件 #如果数据库文件不存在,回新建一个,如果存在则打开此文件 conn = sqlite3.connect('example') c = conn.cursor() #创建表格 c.execute('''create table stocks (date text, trans text, symbol text, qty real, price real)''') # 插入数据,执行SQL语句 c.execute("""insert into stocks values ('2006-01-15','BUoY','RHATd',100,35.14)""") #将变动保存到数据库文件,如果没有执行词语句,则前面的insert 语句操作不会被保存 conn.commit() #得到所有的记录 rec = c.execute('''select * from stocks''') print c.fetchall()