问题库 Python how-to

Python 如何查询 SQLite

快速答案

用 sqlite3.connect 打开数据库,参数化查询避免 SQL 注入。

py
import sqlite3
with sqlite3.connect('app.db') as conn:
    rows = conn.execute('select id, name from users where status=?', ('active',)).fetchall()

使用要点

  • 写入数据库前先确认事务边界,失败时回滚。
  • 拼接 SQL 时使用参数绑定,避免把用户输入直接放进语句。

相关内容