Lua 数据库访问
介绍开源 Lua 数据库访问库 LuaSQL 的支持矩阵、通过 LuaRocks 或源码安装各数据库驱动的方法,以及 env -> conn -> cursor:fetch -> close 完整查询与资源释放流程。
学完这一章,你能够
- 介绍开源 Lua 数据库访问库 LuaSQL 的支持矩阵、通过 LuaRocks 或源码安装各数据库驱动的方法,以及 env -> conn -> cursor:fetch -> close 完整查询与资源释放流程。
LuaSQL 概述与 LuaRocks 驱动安装
Lua 访问关系型数据库最经典的开源接口库是 **LuaSQL**,它提供统一抽象层,支持 ODBC、ADO、Oracle、MySQL、SQLite 与 PostgreSQL 六类主流数据库。推荐使用 Lua 官方包管理器 **LuaRocks** 按需安装驱动:类 Unix 系统可通过源码编译并 `sudo make bootstrap` 安装 LuaRocks(并可借 `luarocks install luasocket` 验证环境),Windows 用户可参考官方 Wiki 安装说明(`https://github.com/keplerproject/luarocks/wiki/Installation-instructions-for-Windows`)。随后按目标数据库执行 `luarocks install luasql-sqlite3`、`luasql-postgres`、`luasql-mysql`、`luasql-sqlite` 或 `luasql-odbc`,也可从源码仓库(`https://github.com/keplerproject/luasql`)自行编译。
LuaSQL 连接、游标遍历与资源关闭流程
以连接 MySQL(其他驱动接口完全一致)为例,标准流程分为五步:第一,通过 `local luasql = require "luasql.mysql"` 加载驱动并调用 `env = luasql.mysql()` 创建环境对象;第二,调用 `conn = env:connect(dbname, user, password, host, port)` 建立连接,必要时执行 `conn:execute("SET NAMES UTF8")` 统一字符集;第三,调用 `cur = conn:execute("SELECT * FROM role")` 获取游标对象;第四,循环调用 `row = cur:fetch(row, "a")` 以列名作键的关联表方式逐行拉取记录(若传 `"n"` 则返回 1-based 数字下标数组,传入已有 `row` 表可复用内存减少 GC 压力),格式化写入输出文件直至返回 `nil`;第五,按从内到外的顺序依次关闭文件、游标(`cur:close()`)、连接(`conn:close()`)与环境(`env:close()`),防止连接句柄泄漏。
使用内存 SQLite 离线模拟 LuaSQL 环境、连接、游标 fetch('a'/'n') 与导出关闭全流程
"""Offline Lua 5.4 semantic verification lab for Chapter 23 (database-access)."""
import json
import sqlite3
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Lua 5.4 + sqlite3(:memory:) LuaSQL semantic verifier (lua/MySQL absent)"
class SimulatedLuaSQLCursor:
def __init__(self, cur: sqlite3.Cursor):
self._cur = cur
self._cols = [d[0] for d in (cur.description or [])]
self.closed = False
def fetch(self, table: dict, mode: str = "n"):
row = self._cur.fetchone()
if row is None:
return None
table.clear()
if mode == "a":
for col, val in zip(self._cols, row):
table[col] = val
else:
for idx, val in enumerate(row, start=1):
table[idx] = val
return table
def close(self):
self._cur.close()
self.closed = True
class SimulatedLuaSQLConnection:
def __init__(self, conn: sqlite3.Connection):
self._conn = conn
self.closed = False
def execute(self, sql: str):
cur = self._conn.cursor()
cur.execute(sql)
if cur.description is not None:
return SimulatedLuaSQLCursor(cur)
self._conn.commit()
affected = cur.rowcount
cur.close()
return affected
def close(self):
self._conn.close()
self.closed = True
class SimulatedLuaSQLEnv:
def __init__(self):
self.closed = False
def connect(self, _db_name=":memory:"):
return SimulatedLuaSQLConnection(sqlite3.connect(":memory:"))
def close(self):
self.closed = True
def case_luasql_driver_ecosystem():
supported_dbs = ["ODBC", "ADO", "Oracle", "MySQL", "SQLite", "PostgreSQL"]
luarocks_pkgs = [
"luasql-sqlite3",
"luasql-postgres",
"luasql-mysql",
"luasql-sqlite",
"luasql-odbc",
]
expected = {"supported_db_count": 6, "driver_pkg_count": 5, "all_prefixed_luasql": True}
actual = {
"supported_db_count": len(supported_dbs),
"driver_pkg_count": len(luarocks_pkgs),
"all_prefixed_luasql": all(p.startswith("luasql-") for p in luarocks_pkgs),
}
return {
"name": "luasql_driver_ecosystem",
"summary": "核对 LuaSQL 支持的 6 类数据库及 LuaRocks 5 项常用驱动包安装命令",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_luasql_env_conn_cursor_fetch_export():
# Offline in-memory SQLite simulates LuaSQL env -> conn -> cur:fetch({}, "a") -> file:write -> close
env = SimulatedLuaSQLEnv()
conn = env.connect(":memory:")
conn.execute("CREATE TABLE role (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
conn.execute("INSERT INTO role (id, name) VALUES (1, 'admin'), (2, 'editor'), (3, 'guest')")
cur = conn.execute("SELECT id, name FROM role ORDER BY id")
row = cur.fetch({}, "a")
written_lines = []
with tempfile.TemporaryDirectory() as tmp:
out_file = Path(tmp) / "role.txt"
with out_file.open("w", encoding="utf-8") as fh:
while row is not None:
line = "%d %s\n" % (row["id"], row["name"])
fh.write(line)
written_lines.append(line.strip())
row = cur.fetch(row, "a")
file_content = out_file.read_text(encoding="utf-8")
cur.close()
conn.close()
env.close()
expected = {
"exported_rows": ["1 admin", "2 editor", "3 guest"],
"file_line_count": 3,
"all_resources_closed": True,
}
actual = {
"exported_rows": written_lines,
"file_line_count": len(file_content.splitlines()),
"all_resources_closed": cur.closed and conn.closed and env.closed,
}
return {
"name": "luasql_env_conn_cursor_fetch_export",
"summary": "使用内存 SQLite 离线模拟 LuaSQL env/conn/cur:fetch({}, \"a\") 查询并导出至临时 role.txt 及完整关闭",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_fetch_numeric_vs_alpha_mode():
env = SimulatedLuaSQLEnv()
conn = env.connect(":memory:")
conn.execute("CREATE TABLE item (id INTEGER, title TEXT)")
conn.execute("INSERT INTO item VALUES (10, 'LuaGuide')")
c1 = conn.execute("SELECT id, title FROM item")
row_n = c1.fetch({}, "n")
c1.close()
c2 = conn.execute("SELECT id, title FROM item")
row_a = c2.fetch({}, "a")
c2.close()
conn.close()
env.close()
expected = {
"numeric_mode_1based": {1: 10, 2: "LuaGuide"},
"alpha_mode_named": {"id": 10, "title": "LuaGuide"},
}
actual = {"numeric_mode_1based": row_n, "alpha_mode_named": row_a}
return {
"name": "fetch_numeric_vs_alpha_mode",
"summary": "对比 cur:fetch({}, \"n\") 1-based 数字下标模式与 cur:fetch({}, \"a\") 列名关联表模式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_luasql_driver_ecosystem(),
case_luasql_env_conn_cursor_fetch_export(),
case_fetch_numeric_vs_alpha_mode(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 离线脚本绝不连接宿主机 MySQL,全程基于 sqlite3(':memory:') 与临时目录模拟 LuaSQL env/conn/cur:fetch({}, 'a') 导出 role.txt 并校验句柄全部关闭。
所需环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。
当前源码 SHA256:e2c2a1c4cbf169fc8b31ccc0d6585e04f461ada9a5fdf8deb62db280aee7e855
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。
ZIP SHA256:3f2aa25ac1aa4d4c6acbcaad4ce9e97238cb48698712fa2c6c9daa77d8adfff9
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 LuaSQL 遍历结果集时,`cur:fetch({}, "a")` 与 `cur:fetch({}, "n")` 的返回表结构有什么区别?为什么循环内常把已有的 `row` 传回 `cur:fetch(row, "a")`?
展开参考解答
`"a"` 模式以 SQL 列名为键填充关联表(如 `row.id`、`row.name`),`"n"` 模式以 1-based 整数下标填充数组(如 `row[1]`、`row[2]`);循环内复用同一个 `row` 表可避免每行分配新表,显著降低大结果集遍历时的垃圾回收开销。