"""Offline SQLite verifier for MySQL Chapter 41: Java JDBC (DriverManager, PreparedStatement, DAO, TX) Patterns."""
from contextlib import closing
from dataclasses import dataclass
import json
import sqlite3
import sys
from urllib.parse import parse_qs, urlparse
def make_case(name: str, summary: str, expected, actual) -> dict:
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
@dataclass
class User:
id: int
name: str
email: str
class UserDao:
def __init__(self, conn: sqlite3.Connection) -> None:
self.conn = conn
def insert_user(self, name: str, email: str) -> int:
with closing(self.conn.cursor()) as stmt:
stmt.execute("INSERT INTO users (name, email) VALUES (?, ?)", (name, email))
return stmt.rowcount
def get_user_by_id(self, user_id: int) -> User | None:
with closing(self.conn.cursor()) as stmt:
row = stmt.execute("SELECT id, name, email FROM users WHERE id = ?", (user_id,)).fetchone()
if row:
return User(id=row[0], name=row[1], email=row[2])
return None
def main() -> None:
# 1. JDBC URL parsing & Statement executeQuery / executeUpdate semantics
jdbc_url = "jdbc:mysql://localhost:3306/app_db?useSSL=false&serverTimezone=UTC"
parsed = urlparse(jdbc_url.removeprefix("jdbc:"))
qs = {k: v[0] for k, v in parse_qs(parsed.query).items()}
conn = sqlite3.connect(":memory:", isolation_level=None)
cur = conn.cursor()
cur.execute(
"CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE)"
)
cur.execute("INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')")
exec_update_count = cur.rowcount
query_rows = [list(r) for r in cur.execute("SELECT id, name FROM users").fetchall()]
case1 = make_case(
"jdbc_url_and_statement_crud",
"Verify JDBC URL components (host/port/db/params) and executeUpdate/executeQuery row semantics",
{
"host": "localhost",
"port": 3306,
"database": "app_db",
"params": {"useSSL": "false", "serverTimezone": "UTC"},
"rows_affected": 1,
"query_rows": [[1, "Alice"]],
},
{
"host": parsed.hostname,
"port": parsed.port,
"database": parsed.path.lstrip("/"),
"params": qs,
"rows_affected": exec_update_count,
"query_rows": query_rows,
},
)
# 2. PreparedStatement parameter binding & DAO pattern
dao = UserDao(conn)
inserted = dao.insert_user("张三", "zhangsan@example.com")
found = dao.get_user_by_id(2)
missing = dao.get_user_by_id(999)
case2 = make_case(
"jdbc_prepared_statement_and_dao",
"Verify PreparedStatement ? binding and UserDao encapsulation return expected User or None",
{
"inserted": 1,
"found": {"id": 2, "name": "张三", "email": "zhangsan@example.com"},
"missing": None,
},
{
"inserted": inserted,
"found": {"id": found.id, "name": found.name, "email": found.email} if found else None,
"missing": missing,
},
)
# 3. Transaction pattern mirroring setAutoCommit(false) -> commit/rollback -> finally setAutoCommit(true)
cur.execute("CREATE TABLE accounts (id INT PRIMARY KEY, balance INT CHECK (balance >= 0))")
cur.executemany("INSERT INTO accounts VALUES (?, ?)", [(1, 400), (2, 100)])
def jdbc_transfer(from_id: int, to_id: int, amount: int) -> tuple[bool, bool]:
auto_commit = False
cur.execute("BEGIN")
try:
cur.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (amount, from_id))
cur.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", (amount, to_id))
cur.execute("COMMIT")
ok = True
except sqlite3.IntegrityError:
cur.execute("ROLLBACK")
ok = False
finally:
auto_commit = True
return ok, auto_commit
ok1, ac1 = jdbc_transfer(1, 2, 100)
ok2, ac2 = jdbc_transfer(1, 2, 999)
final_bal = [list(r) for r in cur.execute("SELECT id, balance FROM accounts ORDER BY id").fetchall()]
case3 = make_case(
"jdbc_transaction_autocommit_toggle",
"Verify setAutoCommit(false)/commit/rollback/finally restoration maintains account consistency",
{
"first": [True, True],
"second": [False, True],
"balances": [[1, 300], [2, 200]],
},
{
"first": [ok1, ac1],
"second": [ok2, ac2],
"balances": final_bal,
},
)
# 4. try-with-resources automatic closure & structured SQL exception diagnostics
diag = {}
with closing(sqlite3.connect(":memory:")) as scoped_conn:
scoped_conn.execute("CREATE TABLE t (k INT PRIMARY KEY)")
scoped_conn.execute("INSERT INTO t VALUES (1)")
try:
scoped_conn.execute("INSERT INTO t VALUES (1)")
except sqlite3.IntegrityError as exc:
diag = {
"error_type": type(exc).__name__,
"error_code": exc.sqlite_errorcode,
"has_message": bool(str(exc)),
}
closed_after_scope = False
try:
scoped_conn.execute("SELECT 1")
except sqlite3.ProgrammingError:
closed_after_scope = True
case4 = make_case(
"jdbc_try_with_resources_and_exception",
"Verify scoped connection auto-closes and SQL exception provides type, error code, and message",
{
"error_type": "IntegrityError",
"has_error_code": True,
"has_message": True,
"closed_after_scope": True,
},
{
"error_type": diag.get("error_type"),
"has_error_code": isinstance(diag.get("error_code"), int),
"has_message": diag.get("has_message"),
"closed_after_scope": closed_after_scope,
},
)
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-java-intro-lab/explore-java-intro.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-java-intro.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联41章) · 含当前章节或实例 · mbskycom202612a1590.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1609.zip