Python自帶一個輕量級的關系型數據庫SQLite。這一數據庫使用SQL語言。SQLite作為后端數據庫,可以搭配Python建網站,或者制作有數據存儲需求的工具。SQLite還在其它領域有廣泛的應用,比如HTML5和移動端。Python標準庫中的sqlite3提供該數據庫的接口。
我將創建一個簡單的關系型數據庫,為一個書店存儲書的分類和價格。數據庫中包含兩個表:category用于記錄分類,book用于記錄某個書的信息。一本書歸屬于某一個分類,因此book有一個外鍵(foreign key),指向catogory表的主鍵id。
創建數據庫
我首先來創建數據庫,以及數據庫中的表。在使用connect()連接數據庫后,我就可以通過定位指針cursor,來執行SQL命令:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
# 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的數據庫是一個磁盤上的文件,如上面的test.db,因此整個數據庫可以方便的移動或復制。test.db一開始不存在,所以SQLite將自動創建一個新文件。
利用execute()命令,我執行了兩個SQL命令,創建數據庫中的兩個表。創建完成后,保存并斷開數據庫連接。
插入數據
上面創建了數據庫和表,確立了數據庫的抽象結構。下面將在同一數據庫中插入數據:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
# 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() |
插入數據同樣可以使用execute()來執行完整的SQL語句。SQL語句中的參數,使用"?"作為替代符號,并在后面的參數中給出具體值。這里不能用Python的格式化字符串,如"%s",因為這一用法容易受到SQL注入攻擊。
我也可以用executemany()的方法來執行多次插入,增加多個記錄。每個記錄是表中的一個元素,如上面的books表中的元素。
查詢
在執行查詢語句后,Python將返回一個循環器,包含有查詢獲得的多個記錄。你循環讀取,也可以使用sqlite3提供的fetchone()和fetchall()方法讀取記錄:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# 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) |
更新與刪除
你可以更新某個記錄,或者刪除記錄:
1
2
3
4
5
6
7
8
9
10
|
# 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() |
你也可以直接刪除整張表:
1
|
c.execute( 'DROP TABLE book' ) |
如果刪除test.db,那么整個數據庫會被刪除。
總結
sqlite3只是一個SQLite的接口。想要熟練的使用SQLite數據庫,還需要學習更多的關系型數據庫的知識。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/vamei/p/3794388.html