Welcome 微信登录

首页 / 数据库 / MySQL / 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)Oracle中where子句和having子句中的区别Hive与MySQL安装配置相关资讯      python  SQLite3  python sqlite3 
  • SQLite3简单操作  (01月29日)
  • Python 决定迁移到 GitHub  (01月03日)
  • Python面试必须要看的15个问题  (11/26/2015 22:23:21)
  • Python 为什么要迁移到 Github  (01月26日)
  • Python 程序员最常犯的十个错误  (12/11/2015 18:32:46)
  • Python 面向对象编程  (10/06/2015 21:19:35)
本文评论 查看全部评论 (0)
表情: 姓名: 字数