当前位置:数据库 > SQLite >>

Python操作SQLite备忘

SQLite百度百科摘录:
http://baike.baidu.com/view/19310.htm

SQLite,是一款轻型的数据库,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。

它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口。

PS:单数据存储文件(类似微软的Access),支持数据库大小至2TB,支持多种开发语言,C, PHP, Perl, Java, ASP .NET,Python。


Python操作SQLite的库PySQLite已经被包括在Python2.5以后的标准库中了,可以方便的使用。

下面是Python操作SQLite的示例代码:


# coding:utf-8
# Practice of oprating SQLite with Python
# by redice 2010.11.09

import sys
reload(sys)
sys.setdefaultencoding(utf-8)

import sqlite3

# 连接数据库,数据库文件不存在则创建
conn = sqlite3.connect("users.db")
conn.text_factory = lambda x: unicode(x, utf-8, replace)
curs = conn.cursor()

# 检查users表是否存在,不存在则创建
# 很强大,不需要使用管理工具事先创建
curs.execute(CREATE TABLE if not exists users(username VARCHAR(20) UNIQUE,password VARCHAR(32),groupe INTEGER);)
# 对数据库有修改的操作要调用commit提交事务
conn.commit()

# insert data
# 采用这种方法插入数据,不用担心数据要转义。数据库接口会自动帮你转义
curs.execute("insert into users values(?,?,?);", (redice,123456,1))
curs.execute("insert into users values(?,?,?);", (qipeng,123456,0))
curs.execute("insert into users values(?,?,?);", (zhangsan,123456,0))
curs.execute("insert into users values(?,?,?);", (laowu,123456,0))
curs.execute("insert into users values(?,?,?);", (lisi,123456,0))
curs.execute("insert into users values(?,?,?);", (wangwu,123456,0))     
conn.commit()
       
# 查找数据
# 对数据库没有修改的操作不需要用commit提交事务
curs.execute("select * from users where username=?;" ,(raw_input("请输入要查询的用户名称:"),))
row = curs.fetchone()
if row:
    print row

conn.close()

运行结果:


附上一个SQLite GUI管理工具 SQLiteManager(with sn) (PS:很像Mysql Administrator)

http://www.redicecn.com/uploads/files/month_201011/SQLiteManagerSetup_with_sn.rar


 

补充:Web开发 , Python ,
Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,