手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python 之SQLite3

[日期:2013-01-04] 来源:Linux社区  作者:tianxicool [字体:大 中 小]

(翻译自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)

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款