--
參考資源
--
認識 SQLite 3
SQLite 3 使用在程式內,也就是 SQLite 並不是像 MySQL 或 Redis 一樣是 Server Client 的架構,需要先安裝 Server 在主機上,然後使用 Client 去使用。是直接使用程式去存取資料庫,實體上就是一個檔案,一個檔案就代表整個資料庫。
因為只是一個檔案,所以 SQLite 3 建議不推薦使用在多人同時環境上,因為 SQLite 3 同時間只能一個寫入動作,
--
安裝
SQLite 3 不需要安裝,只要程式有支援就可以直接使用。Hoyo 在架構設計時還是需要 GUI 輔助,所以會安裝 DB Browser for SQLite 來使用。
--
連接資料庫
Python 3 內建 SQLite 3,因此可以直接使用
|
import sqlite3 conn = sqlite3.connect('Game.sqlite3', isolation_level=None) |
在正式資料存取時,建議將資料庫連接包裝成一個 function
|
def db_connect(self): try: conn = sqlite3.connect('Game.db', isolation_level=None) conn.row_factory = sqlite3.Row # 加上欄位名稱 return conn.cursor() except Exception as e: logging.error(e) |
- isolation_level=None
設定 autocommit 也就是關閉了 Transaction 交易功能,根據程式需求設定,預設是啟用 Transaction
- row_factory = sqlite3.Row
表示回傳欄位名稱,因為 Hoyo 覺得使用順位 0 1 2 3 寫程式很反人類
--
搜尋一筆資料
|
sql = " SELECT * FROM Player WHERE (RoomId, UserId)=(:RoomId, :UserId) " cursor_select.execute(sql, { 'Card1': deck['Number'], 'RoomId': j['room_id'], 'UserId': j['user_id'], }) check = cursor_select.fetchone() player_name = check['Name'] |
- fetchone() 只取一筆資料
- 因為設定了 sqlite3.Row 所以取資料時就是使用欄位名稱
- :RoomId
在 Prepared Statement 也是使用名稱,? 也是反人類
--
搜尋多筆資料
|
cursor_select = self.db_connect() sql = " SELECT * FROM Room WHERE Status=0 " cursor_select.execute(sql) room_rows = cursor_select.fetchall() for row in room_rows: print(row) |
- 使用 fetchall() 就是取得 SELECT 所有資料
--
插入
|
from contextlib import closing with closing(self.db_connect()) as cursor: sql = " INSERT INTO Deck ( RoomId, Number ) VALUES ( :RoomId, :Number ) " cursor.execute(sql, { 'RoomId': j['room_id'], 'Number': int(c), }) |
- SQLite 3 寫入都需要關閉資料庫,表示確定寫入,在此使用 closing,一般使用 close()
--
修改
|
from contextlib import closing with closing(self.db_connect()) as cursor: sql = " UPDATE Player SET Card2=:Card2 WHERE (RoomId, UserId)=(:RoomId, :UserId) " cursor.execute(sql, { 'Card2': deck['Number'], 'RoomId': j['room_id'], 'UserId': j['user_id'], }) |
--
刪除
|
from contextlib import closing with closing(self.db_connect()) as cursor: sql = " DELETE FROM Room WHERE RoomId=:RoomId " cursor.execute(sql, { 'RoomId': j['room_id'], }) |
--
1,511 total views, 2 views today