Solar2d中能否用Lua读取SQL表?sqlite3插件使用咨询
Solar2d 环境下使用Lua读取SQLite表的实现说明
首先明确结论:完全可以通过官方sqlite3插件在Solar2d的Lua代码中完成SQLite表的读取、写入等全部操作,无需额外集成原生模块,具体使用流程如下:
第一步:启用sqlite3插件
Solar2d的插件需要在项目根目录的build.settings文件中声明配置,配置完成后重启编辑器,构建项目时会自动集成对应插件:
-- build.settings 配置示例 settings = { plugins = { ["sqlite3"] = { publisherId = "com.coronalabs" }, }, }
第二步:引入插件并打开数据库
首先在Lua代码中引入插件模块:local sqlite3 = require("sqlite3")
根据使用场景的不同,数据库的打开方式分为两种:
- 打开沙盒可读写数据库:如果需要对数据库执行增删改操作,需将数据库放在应用的Documents可写目录下,打开时若文件不存在会自动创建空数据库:
-- 打开/创建Documents目录下的可写数据库 local dbPath = system.pathForFile("myAppData.db", system.DocumentsDirectory) local db = sqlite3.open(dbPath) -- 打开失败时的基础校验 if not db then print("数据库打开失败") return end
- 读取项目内置只读数据库:如果是提前制作好、直接打包到项目资源里的预建数据库,使用ResourceDirectory路径打开即可,该场景下数据库仅支持读取,不支持写入操作:
-- 读取项目根目录下的预建只读数据库 local dbPath = system.pathForFile("prebuilt.db", system.ResourceDirectory) local db = sqlite3.open(dbPath)
如果需要对内置预建数据库进行修改,需要在应用首次启动时将数据库文件从ResourceDirectory拷贝到Documents可写目录,后续操作都使用拷贝后的副本,示例代码:
-- 首次启动时拷贝内置数据库到可写目录 local srcPath = system.pathForFile("prebuilt.db", system.ResourceDirectory) local dstPath = system.pathForFile("myAppData.db", system.DocumentsDirectory) -- 检查可写目录是否已存在数据库副本 local dstFile = io.open(dstPath, "r") if not dstFile then -- 不存在则执行拷贝 local srcFile = io.open(srcPath, "rb") local dbContent = srcFile:read("*a") srcFile:close() dstFile = io.open(dstPath, "wb") dstFile:write(dbContent) dstFile:close() end io.close(dstFile) -- 后续直接打开Documents目录下的副本即可读写 local db = sqlite3.open(dstPath)
注意:如果数据库文件存放在ResourceDirectory的子目录下,system.pathForFile的路径参数需要包含子目录路径,比如"data/prebuilt.db",否则会出现文件找不到的错误。
第三步:读取SQL表数据
最常用的读取方式是使用nrows迭代器逐行获取查询结果,返回的行数据会自动以Lua表的形式存储,键名对应SQL查询的列名。
假设数据库中存在user_info表,包含id、username、register_time三个字段,读取全表数据的示例代码:
-- 执行查询语句,逐行遍历结果 for row in db:nrows("SELECT id, username, register_time FROM user_info;") do -- 直接通过列名访问行数据 print("用户ID:" .. row.id) print("用户名:" .. row.username) print("注册时间:" .. row.register_time) end
如果需要将所有查询结果存储为Lua数组方便后续复用,可以自行遍历收集:
local userList = {} for row in db:nrows("SELECT * FROM user_info;") do table.insert(userList, row) end
涉及条件查询时,禁止直接拼接SQL字符串避免注入风险,需使用预编译语句绑定参数,示例:
-- 按用户ID查询单条数据 local targetId = 1001 local query = "SELECT * FROM user_info WHERE id = ?;" local stmt = db:prepare(query) stmt:bind_values(targetId) -- 按顺序绑定占位符参数 for row in stmt:nrows() do print("查询到的用户:" .. row.username) end stmt:finalize() -- 释放预编译语句资源
收尾操作
数据库操作完成后,需要关闭数据库连接释放资源:
db:close()
内容的提问来源于stack exchange,提问作者frankpujo
相关产品推荐
相关产品推荐

