sqlite3.* (数据库)

类型
修订版 版本 2024.3703
关键词 sqlite3, 数据库, sqlite
另请参阅 LuaSQLite 文档
SQLite 语言参考

概述

Solar2D 在所有平台上都支持 SQLite 数据库。LuaSQLite 的文档可以在这里查看。

注意事项

当向 open() 提供文件路径时,请确保使用 system.pathForFile()。仅提供简单的文件名(例如 my.db)在模拟器和设备上无法一致地工作,尤其是在 Android 上。

快速入门

示例

创建表
local sqlite3 = require( "sqlite3" )
local db = sqlite3.open_memory()
 
db:exec[[
  CREATE TABLE test (id INTEGER PRIMARY KEY, content);
  INSERT INTO test VALUES (NULL, 'Hello World');
  INSERT INTO test VALUES (NULL, 'Hello Lua');
  INSERT INTO test VALUES (NULL, 'Hello Sqlite3')
]]
 
print( "version " .. sqlite3.version() )
 
for row in db:nrows("SELECT * FROM test") do
  local t = display.newText( row.content, 20, 30*row.id, nil, 16 )
  t:setFillColor( 1, 0, 1 )
end
打开基于文件的数据库
local sqlite3 = require( "sqlite3" )

-- Open "data.db". If the file doesn't exist, it will be created
local path = system.pathForFile( "data.db", system.DocumentsDirectory )
local db = sqlite3.open( path )   

-- Handle the "applicationExit" event to close the database
local function onSystemEvent( event )
    if ( event.type == "applicationExit" ) then              
        db:close()
    end
end
 
-- Set up the table if it doesn't exist
local tablesetup = [[CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, content, content2);]]
print( tablesetup )
db:exec( tablesetup )
 
-- Add rows with an auto index in 'id'. You don't need to specify a set of values because we're populating all of them.
local testvalue = {}
testvalue[1] = "Hello"
testvalue[2] = "World"
testvalue[3] = "Lua"
local tablefill = [[INSERT INTO test VALUES (NULL, ']]..testvalue[1]..[[',']]..testvalue[2]..[['); ]]
local tablefill2 = [[INSERT INTO test VALUES (NULL, ']]..testvalue[2]..[[',']]..testvalue[1]..[['); ]]
local tablefill3 = [[INSERT INTO test VALUES (NULL, ']]..testvalue[1]..[[',']]..testvalue[3]..[['); ]]
db:exec( tablefill )
db:exec( tablefill2 )
db:exec( tablefill3 )
 
-- Print the SQLite version
print( "SQLite version " .. sqlite3.version() )
 
-- Print the table contents
for row in db:nrows("SELECT * FROM test") do
    local text = row.content .. " " .. row.content2
    local t = display.newText( text, 20, 30*row.id, nil, 16 )
    t:setFillColor( 1, 0, 1 )
end

-- Setup the event listener to catch "applicationExit"
Runtime:addEventListener( "system", onSystemEvent )