如何通过Lua程序在Corona SDK中创建数据库和表?

我刚开始学习Lua编程,还不知道如何创建数据库,包括创建表格和检索数据。我想创建一个数据库,并且只需在第一次运行时创建表格。我需要将值插入表格中,并从表格中检索这些值列表。因为我是Lua编程的初学者,不知道该如何入手。请大家帮忙或建议我可以参考哪些教程。谢谢!Madan Mohan

原文链接 https://stackoverflow.com/questions/6329653

点赞
stackoverflow用户88888888
stackoverflow用户88888888

我已经按照 http://wiki.garrysmod.com/?title=LUA:SQLite_Tutorial 进行了SQLite & Lua教程,效果不错。在开始之前,你需要安装或复制lua dlls / 模块到系统路径,以便lua db模块能够找到数据库。

LuaSQL 是客户端库的好选择。

http://www.capricorn76.com/c76_scriptengine_docsdk/luasql/index.html

2011-06-13 11:21:49
stackoverflow用户686008
stackoverflow用户686008

你在标签里提到了 Corona,尽管你的问题中没有提到。这很重要,因为 Corona 内置支持 SQLite,但不支持其他类型的数据库。

他们的网站上有关于如何使用数据库功能的文档:http://developer.anscamobile.com/content/data-storage

请注意,他们的示例都使用 [[ ]] 语法进行数据库命令,但我发现使用“ ”更美观且更易于理解。

2011-06-14 11:45:39
stackoverflow用户2524586
stackoverflow用户2524586

这是一个老问题,但我将解释我的做法:

  1. 下载Sqlite Browser(https://github.com/sqlitebrowser/sqlitebrowser/releases
  2. 创建一个空的数据库
  3. 将它放在你的项目文件夹中
  4. 在你的代码中将其复制到system.DocumentsDirectory中:
local function copyDatabase()
    util.copyFile( "model.db", system.ResourceDirectory, db_name, system.DocumentsDirectory, false )
end

util.copyFile:

function M.copyFile( srcName, srcPath, dstName, dstPath, overwrite )

local results = false

local srcPath = M.doesFileExist( srcName, srcPath )

if ( srcPath == false ) then
    return nil  -- nil = source file not found
end

--check to see if destination file already exists
if not ( overwrite ) then
    if ( M.doesFileExist( dstName, dstPath ) ) then
        return 1  -- 1 = file already exists (dont overwrite)
    end
end

--copy the source file to the destination file
local rfilePath = system.pathForFile( srcName, srcPath )
local wfilePath = system.pathForFile( dstName, dstPath )

local rfh = io.open( rfilePath, "rb" )
local wfh = io.open( wfilePath, "wb" )

if not ( wfh ) then
    print( "writeFileName open error!" )
    return false
else
    --read the file from 'system.ResourceDirectory' and write to the destination directory
    local data = rfh:read( "*a" )
    if not ( data ) then
        print( "read error!" )
        return false
    else
        if not ( wfh:write( data ) ) then
            print( "write error!" )
            return false
        end
    end
end

results = 2  -- 2 = file copied successfully!

--clean up file handles
rfh:close()
wfh:close()

return results
end

打开数据库的方法:

local function openDatabase()
    local path = system.pathForFile( db_name, system.DocumentsDirectory )
    db = sqlite3.open( path )
end

创建一些表

local function createTables()
    -- 我不手动创建主键,因为Sqlite为我们创建了ROWID
    db:exec( "CREATE TABLE IF NOT EXISTS categories (category TEXT, description TEXT, icon_location TEXT )" )
end

你可以使用db:exec(db是对数据库的本地变量)轻松地更新和插入记录。如果查询完成且没有任何错误,db:exec将返回0。

2015-09-19 20:04:51