Python自帶一個輕量級的關(guān)系型數(shù)據(jù)庫SQLite。這一數(shù)據(jù)庫使用SQL語言。SQLite作為后端數(shù)據(jù)庫,可以搭配Python建網(wǎng)站,或者制作有數(shù)據(jù)存儲需求的工具。SQLite還在其它領(lǐng)域有廣泛的應(yīng)用,比如HTML5和移動端。Python標(biāo)準(zhǔn)庫中的sqlite3提供該數(shù)據(jù)庫的接口。
我將創(chuàng)建一個簡單的關(guān)系型數(shù)據(jù)庫,為一個書店存儲書的分類和價格。數(shù)據(jù)庫中包含兩個表:category用于記錄分類,book用于記錄某個書的信息。一本書歸屬于某一個分類,因此book有一個外鍵(foreign key),指向catogory表的主鍵id。
創(chuàng)建數(shù)據(jù)庫
我首先來創(chuàng)建數(shù)據(jù)庫,以及數(shù)據(jù)庫中的表。在使用connect()連接數(shù)據(jù)庫后,我就可以通過定位指針cursor,來執(zhí)行SQL命令:
# By Vamei
import sqlite3
# test.db is a file in the working directory.
conn = sqlite3.connect("test.db")
c = conn.cursor()
# create tables
c.execute('''CREATE TABLE category
(id int primary key, sort int, name text)''')
c.execute('''CREATE TABLE book
(id int primary key,
sort int,
name text,
price real,
category int,
FOREIGN KEY (category) REFERENCES category(id))''')
# save the changes
conn.commit()
# close the connection with the database
conn.close()
SQLite的數(shù)據(jù)庫是一個磁盤上的文件,如上面的test.db,因此整個數(shù)據(jù)庫可以方便的移動或復(fù)制。test.db一開始不存在,所以SQLite將自動創(chuàng)建一個新文件。
利用execute()命令,我執(zhí)行了兩個SQL命令,創(chuàng)建數(shù)據(jù)庫中的兩個表。創(chuàng)建完成后,保存并斷開數(shù)據(jù)庫連接。
插入數(shù)據(jù)
上面創(chuàng)建了數(shù)據(jù)庫和表,確立了數(shù)據(jù)庫的抽象結(jié)構(gòu)。下面將在同一數(shù)據(jù)庫中插入數(shù)據(jù):
# By Vamei
import sqlite3
conn = sqlite3.connect("test.db")
c = conn.cursor()
books = [(1, 1, 'Cook Recipe', 3.12, 1),
(2, 3, 'Python Intro', 17.5, 2),
(3, 2, 'OS Intro', 13.6, 2),
]
# execute "INSERT"
c.execute("INSERT INTO category VALUES (1, 1, 'kitchen')")
# using the placeholder
c.execute("INSERT INTO category VALUES (?, ?, ?)", [(2, 2, 'computer')])
# execute multiple commands
c.executemany('INSERT INTO book VALUES (?, ?, ?, ?, ?)', books)
conn.commit()
conn.close()
插入數(shù)據(jù)同樣可以使用execute()來執(zhí)行完整的SQL語句。SQL語句中的參數(shù),使用"?"作為替代符號,并在后面的參數(shù)中給出具體值。這里不能用Python的格式化字符串,如"%s",因?yàn)檫@一用法容易受到SQL注入攻擊。
我也可以用executemany()的方法來執(zhí)行多次插入,增加多個記錄。每個記錄是表中的一個元素,如上面的books表中的元素。
查詢
在執(zhí)行查詢語句后,Python將返回一個循環(huán)器,包含有查詢獲得的多個記錄。你循環(huán)讀取,也可以使用sqlite3提供的fetchone()和fetchall()方法讀取記錄:
# By Vamei
import sqlite3
conn = sqlite3.connect('test.db')
c = conn.cursor()
# retrieve one record
c.execute('SELECT name FROM category ORDER BY sort')
print(c.fetchone())
print(c.fetchone())
# retrieve all records as a list
c.execute('SELECT * FROM book WHERE book.category=1')
print(c.fetchall())
# iterate through the records
for row in c.execute('SELECT name, price FROM book ORDER BY sort'):
print(row)
更新與刪除
你可以更新某個記錄,或者刪除記錄:
# By Vamei
conn = sqlite3.connect("test.db")
c = conn.cursor()
c.execute('UPDATE book SET price=? WHERE id=?',(1000, 1))
c.execute('DELETE FROM book WHERE id=2')
conn.commit()
conn.close()
你也可以直接刪除整張表:
c.execute('DROP TABLE book')
如果刪除test.db,那么整個數(shù)據(jù)庫會被刪除。
總結(jié)
sqlite3只是一個SQLite的接口。想要熟練的使用SQLite數(shù)據(jù)庫,還需要學(xué)習(xí)更多的關(guān)系型數(shù)據(jù)庫的知識。