如果提到資料, 很多時會想起 MySQL, MariaDB, PostgreSQL 等, 而 SQLite 是一個輕量嵌入式資料庫, 它包含在一個相對小的 C 程式庫裡面, 並支援大多數 SQL 標準。
跟 MySQL 這些資料庫系統不同, SQLite 不會以系統服務的方式執行.
Python 預設內建的 Sqlite3 模組可以對 sqlsite 資料庫管理。
連接資料庫
以下 Python 程式碼會連接 sqlsite 資料庫, 如果 sqlsite 的資料庫不存在, 它會自動建立:
1 2 3 4 5 6 7 |
#!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Database connected!"; |
建立資料表
一般上可以在系統安裝 SQLite 的工具, 用作建立或管理資料表, 如果沒有的話, 在 Python 也可以建立資料表, 跟執行 sqlite 指令一樣, 使用 execute(), 而建立資料表的語法跟 MySQL 差不多:
1 2 3 4 5 6 7 8 9 10 11 |
#!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Database connected!"; conn.execute('create table user (id varchar(20) primary key, name varchar(20), email varchar(50))') print "Created table user"; conn.close() |
當以上程式執行後, 會建立 “user” 資料表.
插入資料
插入資料同樣使用 execute(), 只是在插入資料後執行 commit():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Database connected!"; conn.execute("insert into user values (1, 'member1', 'member1@email.tld')"); conn.execute("insert into user values (2, 'member2', 'member2@email.tld')"); conn.execute("insert into user values (3, 'member3', 'member3@email.tld')"); conn.commit() print "Created records"; conn.close() |
SELECT 讀取資料
以下是在 Sqlite 資料庫讀取資料的寫法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Database connected!"; cursor = conn.execute("SELECT id, name, email from user") for row in cursor: print "ID = ", row[0] print "Name = ", row[1] print "Email = ", row[2], "\n" conn.close() |
UPDATE 更新資料
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Database connected!"; conn.execute("UPDATE user set name = 'new-name' where id = 1") conn.commit() print "Total number of rows updated :", conn.total_changes print "Operation done successfully"; conn.close() |
DELETE 刪除資料
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; conn.execute("DELETE from user where id = 2;") conn.commit() print "Total number of rows deleted :", conn.total_changes print "Operation done successfully"; conn.close() |