"""SQL 语法离线实验:验证大小写不敏感、分号多语句、DML/DDL 全类命令与分组连接去重。"""
import json
import platform
import sqlite3
def run() -> dict:
conn = sqlite3.connect(":memory:")
cases = []
# Case 1: Table setup, case insensitivity, semicolon batching, UTF-8 encoding
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
);
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');
"""
)
upper_rows = conn.execute("SELECT id, name FROM Websites ORDER BY id;").fetchall()
lower_rows = conn.execute("select id, name from websites order by id;").fetchall()
encoding = conn.execute("PRAGMA encoding;").fetchone()[0]
exp1 = {
"row_count": 5,
"case_insensitive_equal": True,
"encoding": "UTF-8",
"columns": ["id", "name", "url", "alexa", "country"],
}
act1 = {
"row_count": len(upper_rows),
"case_insensitive_equal": upper_rows == lower_rows,
"encoding": encoding,
"columns": [r[1] for r in conn.execute("PRAGMA table_info(Websites);").fetchall()],
}
cases.append(
{
"name": "table_inspection_and_case_insensitivity",
"summary": "验证 Websites 5 列 5 行结构、关键字大小写不敏感、分号分隔多语句与 UTF-8 编码",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
}
)
# Case 2: DML SELECT / INSERT INTO / UPDATE / DELETE
conn.execute(
"INSERT INTO Websites (name, url, alexa, country) VALUES ('百度', 'https://www.baidu.com/', 4, 'CN');"
)
conn.execute("UPDATE Websites SET alexa = 5 WHERE name = '百度';")
updated_alexa = conn.execute(
"SELECT alexa FROM Websites WHERE name = '百度';"
).fetchone()[0]
conn.execute("DELETE FROM Websites WHERE name = '百度';")
remaining = conn.execute("SELECT COUNT(*) FROM Websites;").fetchone()[0]
ordered_cn = [
r[0]
for r in conn.execute(
"SELECT name FROM Websites WHERE country = 'CN' ORDER BY alexa ASC;"
).fetchall()
]
exp2 = {
"updated_alexa": 5,
"remaining_after_delete": 5,
"ordered_cn_names": ["淘宝", "微博", "蓝色天空"],
}
act2 = {
"updated_alexa": updated_alexa,
"remaining_after_delete": remaining,
"ordered_cn_names": ordered_cn,
}
cases.append(
{
"name": "dml_select_insert_update_delete",
"summary": "实测 INSERT INTO、UPDATE、DELETE 及带 WHERE/ORDER BY 的 SELECT 语句",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
}
)
# Case 3: DDL CREATE TABLE / ALTER TABLE ADD & DROP COLUMN / CREATE & DROP INDEX / DROP TABLE
conn.execute(
"""
CREATE TABLE audit_items (
item_id INTEGER PRIMARY KEY,
title TEXT NOT NULL
);
"""
)
conn.execute("ALTER TABLE audit_items ADD COLUMN note TEXT;")
cols_after_add = [
r[1] for r in conn.execute("PRAGMA table_info(audit_items);").fetchall()
]
conn.execute("CREATE INDEX idx_audit_title ON audit_items (title);")
idx_after_create = [
r[1] for r in conn.execute("PRAGMA index_list(audit_items);").fetchall()
]
conn.execute("DROP INDEX idx_audit_title;")
idx_after_drop = [
r[1] for r in conn.execute("PRAGMA index_list(audit_items);").fetchall()
]
conn.execute("ALTER TABLE audit_items DROP COLUMN note;")
cols_after_drop = [
r[1] for r in conn.execute("PRAGMA table_info(audit_items);").fetchall()
]
conn.execute("DROP TABLE audit_items;")
exists_after_drop = conn.execute(
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='audit_items';"
).fetchone()[0]
exp3 = {
"cols_after_add": ["item_id", "title", "note"],
"idx_after_create": ["idx_audit_title"],
"idx_after_drop": [],
"cols_after_drop": ["item_id", "title"],
"exists_after_drop": 0,
}
act3 = {
"cols_after_add": cols_after_add,
"idx_after_create": idx_after_create,
"idx_after_drop": idx_after_drop,
"cols_after_drop": cols_after_drop,
"exists_after_drop": exists_after_drop,
}
cases.append(
{
"name": "ddl_table_alter_index_drop",
"summary": "实测 CREATE TABLE、ALTER TABLE 增删列、CREATE/DROP INDEX 与 DROP TABLE",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
}
)
# Case 4: WHERE, ORDER BY, GROUP BY, HAVING, JOIN, DISTINCT
conn.executescript(
"""
CREATE TABLE access_log (
aid INTEGER PRIMARY KEY,
site_id INTEGER NOT NULL,
count INTEGER NOT NULL
);
INSERT INTO access_log VALUES (1, 1, 45), (2, 3, 100), (3, 1, 230), (4, 2, 10);
"""
)
grouped = conn.execute(
"""
SELECT country, COUNT(*) AS cnt
FROM Websites
GROUP BY country
HAVING COUNT(*) >= 2
ORDER BY cnt DESC, country ASC;
"""
).fetchall()
joined = conn.execute(
"""
SELECT w.name, a.count
FROM Websites AS w
INNER JOIN access_log AS a ON w.id = a.site_id
ORDER BY a.aid ASC;
"""
).fetchall()
distinct_countries = [
r[0]
for r in conn.execute(
"SELECT DISTINCT country FROM Websites ORDER BY country ASC;"
).fetchall()
]
exp4 = {
"grouped_having": [["CN", 3], ["USA", 2]],
"joined_rows": [["Google", 45], ["蓝色天空", 100], ["Google", 230], ["淘宝", 10]],
"distinct_countries": ["CN", "USA"],
}
act4 = {
"grouped_having": [list(r) for r in grouped],
"joined_rows": [list(r) for r in joined],
"distinct_countries": distinct_countries,
}
cases.append(
{
"name": "query_clauses_group_having_join_distinct",
"summary": "实测 GROUP BY、HAVING、INNER JOIN 与 SELECT DISTINCT 常用查询子句",
"expected": exp4,
"actual": act4,
"passed": act4 == exp4,
}
)
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-syntax-lab/explore-syntax.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-syntax.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1579.zip