Python 之SQLite3

來源:互聯網
上載者:User

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

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.