Overview

Sqlite3 是一個 Python 控制 SQLite 資料庫的套件。

Usage

Basic

基本使用範例,此處使用字典模式 row_factory = sqlite3.Row 做查詢,預設是 tuple 模式,個人認為字典使用起來比較直觀,不用記哪一筆資料是放在第幾個索引值。

import sqlite3
con = sqlite3.connect('example.db')
con.row_factory = sqlite3.Row
cur = con.cursor()
sql = "SELECT * FROM table_name WHERE column_1='value'"
cur.execute(sql)
result = cur.fetchall()
print(result[0]['column_1'])

Parameter binding with tuple

為了避免使用者輸入意料之外的內容來操作資料庫,也就是 SQL Injection。因此使用 parameter binding 方法,對輸入資料做檢查,避免惡意攻擊。

user_type = 'value'
sql = 'SELECT * FROM table_name WHERE column_1=(?)'
cur.execute(sql, (user_type,))

Parameter binding with dictionary

前一部分提到的 parameter binding 是使用 tuple 做輸入,個人認為也很不值觀,因此也可以使用字典模式做配對。

user_type = 'value'
sql = 'SELECT * FROM table_name WHERE column_1=:column_1'
cur.execute(sql, {'column_1': user_type})

Reference

sqlite3 - DB-API 2.0 interface for SQLite databases - Python 3.9.6 documentation