>  기사  >  데이터 베이스  >  Python 之SQLite3

Python 之SQLite3

WBOY
WBOY원래의
2016-06-07 17:25:06932검색

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

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.