类型 库 修订版 版本 2024.3703 关键词 sqlite3, 数据库, sqlite 另请参阅 LuaSQLite 文档 SQLite 语言参考
Solar2D 在所有平台上都支持 SQLite 数据库。LuaSQLite 的文档可以在这里查看。
当向 open()
提供文件路径时,请确保使用 system.pathForFile()。仅提供简单的文件名(例如 my.db
)在模拟器和设备上无法一致地工作,尤其是在 Android 上。
sqlite3.open( path )
— 打开 SQLite 文件。请注意,路径应该是数据库的完整路径,而不仅仅是文件名。如果发生错误,该函数将返回 nil
、错误代码和错误消息。
sqlite3.version()
— 返回正在使用的 SQLite 版本。返回一个包含 SQLite 版本信息的字符串,格式为 x.y[.z]
。
file:exec( SQL_Command )
— 在数据库中执行 SQL 命令。通常,这用于创建表、插入、更新、追加或从数据库中检索数据。如果发生错误,此函数将返回一个数字 错误代码。
file:nrows( SQL_Command )
— 从 SQL 语句返回连续的行。每次调用迭代器都会返回一个表,其中命名字段对应于数据库中的列。
file:close()
— 关闭数据库。如果发生错误,此函数将返回一个数字 错误代码。
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 )