"""MySQL UPDATE 更新离线实验:在内存 SQLite 中实测单列更新、多列更新、算术表达式更新、无 WHERE 全表更新、相关子查询更新及指定主键更新。"""
import json
import platform
import sqlite3
def run() -> dict:
conn = sqlite3.connect(":memory:")
conn.executescript(
"""
CREATE TABLE employees (employee_id INTEGER PRIMARY KEY, name TEXT, salary REAL);
INSERT INTO employees VALUES (101, 'Alice', 52000), (102, 'Bob', 48000);
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, customer_id INTEGER, status TEXT, ship_date TEXT, amount REAL);
INSERT INTO orders VALUES
(1001, 1, 'Pending', NULL, 200.0),
(1002, 1, 'Paid', '2023-02-10', 350.0),
(1003, 2, 'Paid', '2023-02-12', 120.0);
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, category TEXT, price REAL);
INSERT INTO products VALUES
(1, 'Monitor', 'Electronics', 1000.0),
(2, 'Mouse', 'Electronics', 100.0),
(3, 'Desk', 'Furniture', 500.0);
CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, status TEXT);
INSERT INTO students VALUES (1, 'Lin', 'Active'), (2, 'Chen', 'Active');
CREATE TABLE customers (customer_id INTEGER PRIMARY KEY, customer_type TEXT, total_purchases REAL);
INSERT INTO customers VALUES (1, 'Premium', 0.0), (2, 'Standard', 0.0);
CREATE TABLE articles_tbl (
article_id INTEGER PRIMARY KEY,
article_title TEXT NOT NULL,
article_author TEXT NOT NULL,
submission_date TEXT NOT NULL
);
INSERT INTO articles_tbl VALUES
(1, '学习 PHP', '蓝色天空', '2017-04-12'),
(2, '学习 MySQL', '蓝色天空', '2017-04-12'),
(3, 'JAVA 教程', 'MBSKY.COM', '2016-05-06');
"""
)
cases = []
# Case 1: Single-column & multi-column UPDATE with WHERE
c1 = conn.execute("UPDATE employees SET salary = 60000 WHERE employee_id = 101;")
c2 = conn.execute(
"UPDATE orders SET status = 'Shipped', ship_date = '2023-03-01' WHERE order_id = 1001;"
)
emp_salaries = [
list(r)
for r in conn.execute(
"SELECT employee_id, salary FROM employees ORDER BY employee_id;"
).fetchall()
]
order_1001 = list(
conn.execute(
"SELECT order_id, status, ship_date FROM orders WHERE order_id = 1001;"
).fetchone()
)
exp1 = {
"emp_rowcount": 1,
"order_rowcount": 1,
"emp_salaries": [[101, 60000.0], [102, 48000.0]],
"order_1001": [1001, "Shipped", "2023-03-01"],
}
act1 = {
"emp_rowcount": c1.rowcount,
"order_rowcount": c2.rowcount,
"emp_salaries": emp_salaries,
"order_1001": order_1001,
}
cases.append(
{
"name": "update_single_and_multiple_columns",
"summary": "实测按主键条件执行单列更新(salary)与多列更新(status、ship_date)",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
}
)
# Case 2: Expression update (price * 1.1) and full-table update without WHERE
conn.execute("UPDATE products SET price = ROUND(price * 1.1, 2) WHERE category = 'Electronics';")
c_all = conn.execute("UPDATE students SET status = 'Graduated';")
prices = [
list(r) for r in conn.execute("SELECT name, price FROM products ORDER BY id;").fetchall()
]
stu_statuses = [
r[0] for r in conn.execute("SELECT status FROM students ORDER BY id;").fetchall()
]
exp2 = {
"prices": [["Monitor", 1100.0], ["Mouse", 110.0], ["Desk", 500.0]],
"all_students_updated_count": 2,
"student_statuses": ["Graduated", "Graduated"],
}
act2 = {
"prices": prices,
"all_students_updated_count": c_all.rowcount,
"student_statuses": stu_statuses,
}
cases.append(
{
"name": "update_expression_and_without_where_warning",
"summary": "实测表达式涨价更新与省略 WHERE 子句导致整表全部记录被修改的效果",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
}
)
# Case 3: Correlated subquery UPDATE + targeted CLI/PHP update simulation
conn.execute(
"""
UPDATE customers
SET total_purchases = (
SELECT SUM(amount)
FROM orders
WHERE orders.customer_id = customers.customer_id
)
WHERE customer_type = 'Premium';
"""
)
cust_totals = [
list(r)
for r in conn.execute(
"SELECT customer_id, customer_type, total_purchases FROM customers ORDER BY customer_id;"
).fetchall()
]
conn.execute("UPDATE articles_tbl SET article_title = '学习 C++' WHERE article_id = 3;")
title_after_cli = conn.execute(
"SELECT article_title FROM articles_tbl WHERE article_id = 3;"
).fetchone()[0]
conn.execute(
"UPDATE articles_tbl SET article_title = ? WHERE article_id = ?;",
("学习 Python", 3),
)
title_after_php_equiv = conn.execute(
"SELECT article_title FROM articles_tbl WHERE article_id = 3;"
).fetchone()[0]
exp3 = {
"customer_totals": [[1, "Premium", 550.0], [2, "Standard", 0.0]],
"article_3_after_first_update": "学习 C++",
"article_3_after_second_update": "学习 Python",
}
act3 = {
"customer_totals": cust_totals,
"article_3_after_first_update": title_after_cli,
"article_3_after_second_update": title_after_php_equiv,
}
cases.append(
{
"name": "update_subquery_and_targeted_row",
"summary": "实测相关子查询汇总更新 Premium 客户消费总额以及按主键定向更新文章标题",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
}
)
conn.close()
return {
"version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
"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/mysql-update-query-lab/explore-update-query.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-update-query.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联41章) · 含当前章节或实例 · mbskycom202612a1590.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1627.zip