首頁  >  文章  >  後端開發  >  Python標準函式庫14 資料庫 (sqlite3)

Python標準函式庫14 資料庫 (sqlite3)

高洛峰
高洛峰原創
2016-11-23 11:39:111340瀏覽

Python自帶一個輕量級的關係型資料庫SQLite。這個資料庫使用SQL語言。 SQLite作為後端資料庫,可以搭配Python建立網站,或是製作有資料儲存需求的工具。 SQLite在其它領域也有廣泛的應用,例如HTML5和行動端。 Python標準函式庫中的sqlite3提供該資料庫的介面。

我將建立一個簡單的關係型資料庫,為一個書店儲存書的分類和價格。資料庫中包含兩個表格:category用來記錄分類,book用來記錄某個書的資訊。一本書歸屬於某一個分類,因此book有一個外鍵(foreign key),指向catogory表的主鍵id。

Python標準函式庫14 資料庫 (sqlite3)

建立資料庫

我首先來建立資料庫,以及資料庫中的表。在使用connect()連接資料庫後,我就可以透過定位指標cursor,來執行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的資料庫是一個磁碟上的文件,如上面的test.db,因此整個資料庫可以方便的移動或複製。 test.db一開始不存在,所以SQLite會自動建立一個新檔案。

利用execute()指令,我執行了兩個SQL指令,建立資料庫中的兩個表。創建完成後,儲存並斷開資料庫連線。

 

插入資料

上面建立了資料庫和表格,確立了資料庫的抽象結構。以下將在同一資料庫插入資料:

# 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()方法讀取記錄:

# 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,那麼整個資料庫就會被刪除。

 

總結

sqlite3只是一個SQLite的介面。想要熟練的使用SQLite資料庫,還需要學習更多的關係型資料庫的知識。


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:Python 簡介下一篇:Python 簡介