蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在本地 SQLite 3.53.1 实测 DDL/DML 生命周期、目录检视、表结构与索引维护及事务提交回滚

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。explore-command-manual.py
explore-command-manual.py135 行
"""Offline SQLite verifier for MySQL Chapter 36: Command Reference Manual."""
import json
import sqlite3
import sys


def make_case(name: str, summary: str, expected, actual) -> dict:
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    conn = sqlite3.connect(":memory:", isolation_level=None)
    cur = conn.cursor()

    # 1. Basic DDL & DML command lifecycle (CREATE/INSERT/SELECT/UPDATE/DELETE/DROP)
    cur.execute(
        "CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL NOT NULL)"
    )
    cur.execute("INSERT INTO products (id, name, price) VALUES (1, 'Book', 50.0), (2, 'Pen', 5.0)")
    cur.execute("UPDATE products SET price = 45.0 WHERE id = 1")
    selected = [
        list(r)
        for r in cur.execute("SELECT id, name, price FROM products WHERE price >= 10").fetchall()
    ]
    cur.execute("DELETE FROM products WHERE id = 2")
    remaining = cur.execute("SELECT COUNT(*) FROM products").fetchone()[0]
    cur.execute("DROP TABLE products")
    dropped = (
        cur.execute("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='products'").fetchone()[0]
        == 0
    )
    case1 = make_case(
        "basic_ddl_dml_lifecycle",
        "Verify CREATE TABLE, INSERT, SELECT WHERE, UPDATE, DELETE, and DROP TABLE command sequence",
        {
            "selected": [[1, "Book", 45.0]],
            "remaining_after_delete": 1,
            "dropped": True,
        },
        {
            "selected": selected,
            "remaining_after_delete": remaining,
            "dropped": dropped,
        },
    )

    # 2. Catalog inspection commands (SHOW TABLES / DESCRIBE / SHOW CREATE TABLE counterparts)
    cur.execute(
        "CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT NOT NULL UNIQUE, role TEXT DEFAULT 'member')"
    )
    tables = [
        r[0]
        for r in cur.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
        ).fetchall()
    ]
    desc_cols = [r[1] for r in cur.execute("PRAGMA table_info(users)").fetchall()]
    create_sql = cur.execute(
        "SELECT sql FROM sqlite_master WHERE type='table' AND name='users'"
    ).fetchone()[0]
    case2 = make_case(
        "catalog_and_schema_commands",
        "Verify catalog inspection for table list, column description, and CREATE TABLE DDL",
        {
            "tables": ["users"],
            "columns": ["id", "username", "role"],
            "has_unique": True,
        },
        {
            "tables": tables,
            "columns": desc_cols,
            "has_unique": "UNIQUE" in create_sql,
        },
    )

    # 3. Table structure & index commands (ALTER TABLE, CREATE INDEX, DROP INDEX)
    cur.execute("ALTER TABLE users ADD COLUMN email TEXT")
    cur.execute("ALTER TABLE users RENAME COLUMN role TO user_role")
    cur.execute("CREATE INDEX idx_users_email ON users (email)")
    idx_before = [
        r[1] for r in cur.execute("PRAGMA index_list(users)").fetchall() if not r[1].startswith("sqlite_")
    ]
    cur.execute("DROP INDEX idx_users_email")
    idx_after = [
        r[1] for r in cur.execute("PRAGMA index_list(users)").fetchall() if not r[1].startswith("sqlite_")
    ]
    cur.execute("ALTER TABLE users DROP COLUMN email")
    cols_final = [r[1] for r in cur.execute("PRAGMA table_info(users)").fetchall()]
    case3 = make_case(
        "table_alter_and_index_commands",
        "Verify ALTER TABLE ADD/RENAME/DROP COLUMN and CREATE/DROP INDEX commands",
        {
            "idx_before": ["idx_users_email"],
            "idx_after": [],
            "cols_final": ["id", "username", "user_role"],
        },
        {
            "idx_before": idx_before,
            "idx_after": idx_after,
            "cols_final": cols_final,
        },
    )

    # 4. Transaction commands (BEGIN / COMMIT / ROLLBACK)
    cur.execute("BEGIN")
    cur.execute("INSERT INTO users (id, username) VALUES (1, 'alice')")
    cur.execute("COMMIT")
    cur.execute("BEGIN")
    cur.execute("INSERT INTO users (id, username) VALUES (2, 'bob_reverted')")
    cur.execute("ROLLBACK")
    final_users = [r[0] for r in cur.execute("SELECT username FROM users ORDER BY id").fetchall()]
    case4 = make_case(
        "transaction_command_lifecycle",
        "Verify BEGIN/COMMIT persists 'alice' and BEGIN/ROLLBACK discards 'bob_reverted'",
        ["alice"],
        final_users,
    )

    conn.close()
    payload = {
        "version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
        "cases": [case1, case2, case3, case4],
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。

入口文件:projects/mysql-command-manual-lab/explore-command-manual.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-command-manual.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MySQL

课程关联工程包(登记关联41章) · 含当前章节或实例 · mbskycom202612a1590.zip

下载课程关联工程包:MySQL

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1592.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习