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

在本地临时目录实测 SQL 脚本导入、自定义分隔符装载、列序重排与三种冲突模式

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。explore-database-import.py
explore-database-import.py129 行
"""Offline SQLite verifier for MySQL Chapter 33: Importing Data (SQL script, LOAD DATA, column mapping, conflict modes)."""
import csv
import json
import sqlite3
import sys
import tempfile
from pathlib import Path


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:
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)

        # 1. SQL script import (counterpart of mysql < backup.sql and source backup.sql)
        sql_file = root / "backup.sql"
        sql_file.write_text(
            """
            CREATE TABLE courses (id INT PRIMARY KEY, title TEXT NOT NULL);
            INSERT INTO courses VALUES (1, 'MySQL Core'), (2, 'Indexing');
            """,
            encoding="utf-8",
        )
        conn = sqlite3.connect(":memory:")
        conn.executescript(sql_file.read_text(encoding="utf-8"))
        imported_courses = [
            list(r) for r in conn.execute("SELECT id, title FROM courses ORDER BY id").fetchall()
        ]
        case1 = make_case(
            "import_sql_script_batch",
            "Verify executing a .sql backup file creates tables and loads all rows cleanly",
            [[1, "MySQL Core"], [2, "Indexing"]],
            imported_courses,
        )

        # 2. Custom field/line delimiter import (counterpart of LOAD DATA LOCAL INFILE FIELDS ':' LINES '\r\n')
        colon_file = root / "dump.txt"
        colon_file.write_bytes(b"10:alpha:100\r\n20:beta:200\r\n")
        conn.execute("CREATE TABLE mytbl (a INT, b TEXT, c INT)")
        with colon_file.open("r", encoding="utf-8", newline="") as f:
            reader = csv.reader(f, delimiter=":")
            conn.executemany(
                "INSERT INTO mytbl (a, b, c) VALUES (?, ?, ?)",
                [(int(r[0]), r[1], int(r[2])) for r in reader if r],
            )
        colon_rows = [
            list(r) for r in conn.execute("SELECT a, b, c FROM mytbl ORDER BY a").fetchall()
        ]
        case2 = make_case(
            "import_delimited_custom_separators",
            "Verify parsing colon-delimited CRLF text file into target table columns",
            [[10, "alpha", 100], [20, "beta", 200]],
            colon_rows,
        )

        # 3. Reordered column mapping (counterpart of LOAD DATA ... INTO TABLE mytbl (b, c, a) / --columns=b,c,a)
        reordered_file = root / "reordered.txt"
        reordered_file.write_text("beta_val\t99\t1\ngamma_val\t88\t2\n", encoding="utf-8")
        conn.execute("CREATE TABLE mapped_tbl (a INT, b TEXT, c INT)")
        with reordered_file.open("r", encoding="utf-8", newline="") as f:
            reader = csv.reader(f, delimiter="\t")
            # File columns correspond to table columns (b, c, a)
            conn.executemany(
                "INSERT INTO mapped_tbl (b, c, a) VALUES (?, ?, ?)",
                [(r[0], int(r[1]), int(r[2])) for r in reader if r],
            )
        mapped_rows = [
            list(r) for r in conn.execute("SELECT a, b, c FROM mapped_tbl ORDER BY a").fetchall()
        ]
        case3 = make_case(
            "import_reordered_columns",
            "Verify explicit target column list (b, c, a) maps file columns accurately into (a, b, c) table",
            [[1, "beta_val", 99], [2, "gamma_val", 88]],
            mapped_rows,
        )

        # 4. Conflict modes mirroring mysqlimport --ignore (-i), --replace (-r), and --delete (-d)
        conn.execute("CREATE TABLE items (id INT PRIMARY KEY, label TEXT NOT NULL)")
        conn.executemany("INSERT INTO items VALUES (?, ?)", [(1, "orig_1"), (2, "orig_2")])

        incoming = [(2, "new_2"), (3, "new_3")]
        # --ignore
        conn.executemany("INSERT OR IGNORE INTO items VALUES (?, ?)", incoming)
        after_ignore = [list(r) for r in conn.execute("SELECT id, label FROM items ORDER BY id").fetchall()]

        # --replace
        conn.executemany("INSERT OR REPLACE INTO items VALUES (?, ?)", incoming)
        after_replace = [list(r) for r in conn.execute("SELECT id, label FROM items ORDER BY id").fetchall()]

        # --delete (truncate/delete before load)
        conn.execute("DELETE FROM items")
        conn.executemany("INSERT INTO items VALUES (?, ?)", incoming)
        after_delete = [list(r) for r in conn.execute("SELECT id, label FROM items ORDER BY id").fetchall()]

        case4 = make_case(
            "import_conflict_modes_delete_ignore_replace",
            "Verify --ignore skips duplicate keys, --replace overwrites them, and --delete clears prior rows first",
            {
                "after_ignore": [[1, "orig_1"], [2, "orig_2"], [3, "new_3"]],
                "after_replace": [[1, "orig_1"], [2, "new_2"], [3, "new_3"]],
                "after_delete": [[2, "new_2"], [3, "new_3"]],
            },
            {
                "after_ignore": after_ignore,
                "after_replace": after_replace,
                "after_delete": after_delete,
            },
        )
        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-database-import-lab/explore-database-import.py

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

下载课程关联工程包:MySQL

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

下载课程关联工程包:MySQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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