"""SQL DELETE 离线实验:验证带 WHERE 条件删除、全表清空保留表结构与索引及事务回滚恢复。"""
import json
import platform
import sqlite3
def run() -> dict:
conn = sqlite3.connect(":memory:")
conn.isolation_level = None
conn.executescript(
"""
CREATE TABLE websites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
url TEXT NOT NULL,
alexa INTEGER NOT NULL,
country TEXT NOT NULL
);
CREATE INDEX idx_websites_country ON websites (country);
INSERT INTO websites (id, name, url, alexa, country) VALUES
(1, 'Google', 'https://www.google.com/', 1, 'USA'),
(2, '淘宝', 'https://www.taobao.com/', 13, 'CN'),
(3, '蓝色天空', 'http://www.mbsky.com/', 4689, 'CN'),
(4, '微博', 'http://weibo.com/', 20, 'CN'),
(5, 'Facebook', 'https://www.facebook.com/', 3, 'USA');
"""
)
cases = []
# Case 1: Targeted DELETE with WHERE
cur1 = conn.execute(
"DELETE FROM websites WHERE name = 'Facebook' AND country = 'USA';"
)
remaining_names = [
r[0] for r in conn.execute("SELECT name FROM websites ORDER BY id;").fetchall()
]
exp1 = {
"deleted_rowcount": 1,
"remaining_names": ["Google", "淘宝", "蓝色天空", "微博"],
}
act1 = {
"deleted_rowcount": cur1.rowcount,
"remaining_names": remaining_names,
}
cases.append(
{
"name": "delete_targeted_with_where",
"summary": "执行 DELETE FROM websites WHERE name='Facebook' AND country='USA' 仅删除 1 行",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
}
)
# Case 2: DELETE all rows without WHERE preserves table schema & indexes; ROLLBACK restores
conn.execute("BEGIN;")
cur2 = conn.execute("DELETE FROM websites;")
count_after_wipe = conn.execute("SELECT COUNT(*) FROM websites;").fetchone()[0]
cols_still_present = [
r[1] for r in conn.execute("PRAGMA table_info(websites);").fetchall()
]
idx_still_present = [
r[1] for r in conn.execute("PRAGMA index_list(websites);").fetchall()
]
conn.execute("ROLLBACK;")
count_after_rollback = conn.execute("SELECT COUNT(*) FROM websites;").fetchone()[0]
exp2 = {
"wiped_rowcount": 4,
"count_after_wipe": 0,
"columns_preserved": ["id", "name", "url", "alexa", "country"],
"indexes_preserved": ["idx_websites_country"],
"count_after_rollback": 4,
}
act2 = {
"wiped_rowcount": cur2.rowcount,
"count_after_wipe": count_after_wipe,
"columns_preserved": cols_still_present,
"indexes_preserved": idx_still_present,
"count_after_rollback": count_after_rollback,
}
cases.append(
{
"name": "delete_all_rows_preserves_schema_rollback",
"summary": "实测省略 WHERE 清空全部 4 行但保留列定义与索引,并验证 ROLLBACK 恢复数据",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
}
)
# Case 3: Zero-match DELETE
cur3 = conn.execute("DELETE FROM websites WHERE name = 'UnknownSite';")
still_count = conn.execute("SELECT COUNT(*) FROM websites;").fetchone()[0]
exp3 = {"deleted_rowcount": 0, "remaining_count": 4}
act3 = {"deleted_rowcount": cur3.rowcount, "remaining_count": still_count}
cases.append(
{
"name": "delete_zero_match_no_effect",
"summary": "验证 WHERE 条件未命中任何行时 DELETE 返回 rowcount=0 且数据表无改动",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
}
)
conn.close()
return {
"version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version}",
"cases": cases,
}
if __name__ == "__main__":
print(json.dumps(run(), ensure_ascii=False, indent=2))
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/sql-delete-lab/explore-delete.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-delete.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1535.zip
课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip