Luasql和SQLite是什么?

5

我刚开始学习Lua作为一种简单的访问SQLite DLL的方式,但是在尝试使用DB-agnostic LuaSQL模块时遇到了错误:

require "luasql.sqlite"
module "luasql.sqlite"

print("Content-type: Text/html\n")

print("Hello!")

请注意,我正在尝试从最基本的设置开始,所以工作目录中只有以下文件,并且sqlite.dll实际上是来自LuaForge网站的重命名的sqlite3.dll:
C:\Temp的目录
<DIR> luasql
lua5.1.exe
lua5.1.dll
hello.lua
C:\Temp\luasql的目录 sqlite.dll
是否缺少一些二进制文件,这可以解释错误?
谢谢。
编辑:我将DLL重命名为其原始sqlite3.dll,并更新了源以反映此更改(最初是因为在找到的示例中这样称呼它)。
此时,代码如下...
require "luasql.sqlite3"

-- attempt to call field 'sqlite' (a nil value)
env = luasql.sqlite()

env:close()

... and the error message I'm getting:

C:\>lua5.1.exe hello.lua
lua5.1.exe: hello.lua:4: attempt to call field 'sqlite' (a nil value)

编辑:找到了问题所在:应该使用 env = luasql.sqlite3() 而不是 env = luasql.sqlite()。

对于像我这样的新手,以下是一个完整的示例,使用最新的 SQLite LuaSQL 驱动程序

require "luasql.sqlite3"

env = luasql.sqlite3()
conn = env:connect("test.sqlite")

assert(conn:execute("create table if not exists tbl1(one varchar(10), two smallint)"))
assert(conn:execute("insert into tbl1 values('hello!',10)"))
assert(conn:execute("insert into tbl1 values('goodbye',20)"))

cursor = assert(conn:execute("select * from tbl1"))
row = {}
while cursor:fetch(row) do
    print(table.concat(row, '|'))
end

cursor:close()
conn:close()

env:close()

谢谢你。
感谢您的选择。

为什么 DLL 被重命名了?你遇到了什么错误? - Matthew Flaschen
上面给出的示例在 Lua 5.1.4 中会产生以下错误:lua: sql.lua:3: attempt to index global 'luasql' (a nil value)。这是因为 require 不再定义全局变量。将第一行更改为 luasql = require "luasql.sqlite3" 将解决该问题。 - user1704650
2个回答

2
  1. 不要重新命名DLL文件:这会导致Lua找不到DLL中的初始化函数(该函数与DLL同名)。

  2. 您不需要调用module,只需调用require。当您创建模块时才使用module,而不是在使用它时。


编辑:根据LuaSQL文档,看起来您需要调用luasql.sqlite3()而不是luasql.sqlite()


谢谢大家的建议。我已经有了进一步的进展,但仍然遇到错误,因此相应地更新了问题。 - Gulbahar
是的,我最近使用了luasql,它是sqlite3。非常好用。 - gimpf

0
在您编辑的代码片段中,您正在加载luasql.sqlite3模块并尝试访问luasql.sqlite驱动程序。请注意,sqlite3sqlite不同...


是的,发布评论几分钟后就找到了解决方法;-)现在可以完美地运行了。谢谢。 - Gulbahar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接