一、SQLite簡介
SQLite是一個包含在C庫中的輕量級數據庫。它并不需要獨立的維護進程,并且允許使用非標準變體(nonstandard variant)的SQL查詢語句來訪問數據庫。一些應用可是使用SQLite保存內部數據。它也可以在構建應用原型的時候使用,以便于以后轉移到更大型的數據庫,比如PostgreSQL或者Oracle。
sqlite3模塊由Gerhard Häring編寫,提供了一個SQL接口,這個接口的設計遵循了由PEP 249描述的DB-API 2.0說明書。
二、創建并打開數據庫
為了使用這個模塊,必須先創建一個連接(Connection)對象來代表數據庫。在以下的例子中,數據將會被保存在 example.db 文件中:
import sqlite3
conn = sqlite3.connect('example.db')
如果指定的數據庫存在,就會直接打開這個數據庫,否則將新建一再打開。
也可以提供專用名 :memory: 來在內存中建立數據庫。三、數據庫連接對象
一旦擁有了連接(Connection)對象,就可以創建游標(Cursor)對象并調用他的execute()方法來執行SQL語句:
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
保存后的數據是持久的,并且可以在以后的訪問中可用。四、增刪改查
1.建(create)表
c.execute("create table catalog (id integer primary key,pid integer,name varchar(10) UNIQUE,nickname text NULL)")
上面語句創建了一個叫catalog的表,它有一個主鍵id,一個pid,和一個name,name是不可以重復的,以及一個nickname默認為NULL。
2.刪除表(DROP),清空表(TRUNCATE)
c.execute("drop table catalog")
上面語句將catalog表刪除。
另外SQLite中沒有清空表的操作,使用如下方式替代:
c.execute("delete from catalog")
3.插入(insert)數據,更改(uptate)數據
通常SQL語句中會用到python變量作為值(value)。不建議直接使用python的字符串運算來構造查詢語句,因為這樣是不安全的,會使你的程序容易受到SQL注入攻擊。
可以使用DB-API提供的參數代換。在想使用值(value)的地方放置一個'?'作為占位符,然后提供一個由值(value)組成的元組作為游標(cursor)中execute()方法的第二個參數。(其他的數據庫模塊可能使用別的占位符,比如 '%s' 或者 ':1')
# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
c.execute("UPDATE catalog SET trans='SELL' WHERE symbol = 'IBM'")
4.查詢(select)數據
正如前面所說,提倡使用元組進行操作。
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()
5.刪除(delete)數據
t=('RHAT')
c.execute("DELETE * FROM stocks WHERE symbol=?", t)