1. 程式人生 > >Python學習之sqlite3(1)

Python學習之sqlite3(1)

SQLite 是一個軟體庫,實現了自給自足的、無伺服器的、零配置的、事務性的 SQL 資料庫引擎。SQLite 是在世界上最廣泛部署的 SQL 資料庫引擎。SQLite 原始碼不受版權限制。
在Python中,SQLite作為一個內嵌模組使用,如何使用SQLite模組呢??

建立資料庫

為了使用sqlite3資料庫模組,首先得建立一個Connection物件代表資料庫,下面建立一個數據庫example.db。

import sqlite3
conn = sqlite3.connect('example.db')

建立表插入資料

一旦建立Connection物件後,需要建立Cursor物件,然後呼叫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()

查詢插入的資料

剛才插入的資料通過Cursor物件執行SQL語句查詢。

for row in c.execute('SELECT * FROM stocks ORDER BY price'):
        print(row)

輸出結果如下所示:

('2006-01-05', 'BUY', 'RHAT', 100, 35.14)