Python 之SQLite3


(翻译自python v2.7 document)

sqlite是一个c语言库,提供了一个轻量级的文件数据库解决方案。她不需要服务器支持,而且支持非标准的sql语句。

自python2.5之后sqlite被集成到了python标准库中。

一个使用sqlite3的例子:

import sqlite3
conn=sqlite3.connect('example')
##若想创建内存数据库,可以conn=sqlite3.connect(':memory:')
##连接创建好后,再创建游标对象,执行他的execute()方法进行SQL语句执行
c=conn.cursor()
#create a table
c.execute('''create table table1
(date text, trans text, symbol text,
 qty real, price real)''')
#insert a row of data
c.execute('''insert into table1
          values ('2011-01-05','BUY','RHAT',100,35.14)''')
#save the changes
conn.commit()
#we can also close the cursor if we are done with it
c.close()

通常使用SQL操作需要使用python变量。不能直接使用python字符串,因为这面临SQL注入的威胁。使用DB-API的参数来替代,在你想用字符串的地方使用“?”作为一个占位符,然后提供一个元组值作为游标execute()方法的第二个参数(其他的数据库模块可能使用一个不同德占位符,比如"%s" or ":1")。举个例子:

!!这样是危险的!!

# Never do this -- insecure!
symbol = 'IBM'
c.execute("... where symbol = '%s'" % symbol)

这样是符合要求的:

# Do this instead
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)
# Larger example
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
        ]:
    c.execute('insert into stocks values (?,?,?,?,?)', t)

相关内容