This is the standard, **safe way** to open a SQLite database in Python using the `sqlite3` context m

Caf5261 Caf5261 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

This is the standard, safe way to open a SQLite database in Python using the sqlite3 context manager 👍

import sqlite3

with sqlite3.connect(db_path) as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT 1")

What this context manager actually does

BehaviorDetail
✅ Commits automaticallyIf the block finishes without exception, conn.commit() is called
✅ Rolls back on errorIf an exception occurs, conn.rollback() is called
❌ Does not close the connectionThe connection stays open after the with block

⚠️ This is a common surprise. with sqlite3.connect(...) manages transactions, not the connection lifecycle.


from contextlib import closing
import sqlite3

with closing(sqlite3.connect(db_path)) as conn:
    with conn:  # transaction manager (commit / rollback)
        cursor = conn.cursor()
        cursor.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))

Or more concisely (Python 3.7+):

import sqlite3

with sqlite3.connect(db_path) as conn:
    cursor = conn.cursor()
    cursor.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
# connection still open here ⚠️

If you care about closing:

conn = sqlite3.connect(db_path)
try:
    with conn:
        conn.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
finally:
    conn.close()

Quick reference

NeedUse
Auto commit/rollbackwith conn:
Auto closewith closing(sqlite3.connect(...)):
BothNest them (recommended)
Read-onlysqlite3.connect(f"file:{db_path}?mode=ro", uri=True)

Pro tip: row_factory

conn.row_factory = sqlite3.Row
cursor = conn.execute("SELECT * FROM users")
row = cursor.fetchone()
print(row["name"])  # instead of row[1]

If you want, I can also show you a clean reusable DB helper class or how to handle concurrent writes safely.

...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
Caf5261
Borter 10 成员 1,562 内容