I did some test using the sample code from the documentation….
The first problem is that sqlite3.open() will create a new db file if none exists, and it doesn’t tell you if it was able to open an existing file or if it created a new one.
Here’s some code you can use to test with:
local sqlite3 = require( "sqlite3" )
local lfs = require("lfs")
local path = system.pathForFile( "data.db", system.DocumentsDirectory )
local fileInfo = display.newText("File info:", 0, 20, nil, 10)
fileInfo.anchorX = 0
fileInfo.anchorY = 0
local function createDB()
local db = sqlite3.open( path )
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')
]]
db:close()
end
local function checkDBFile()
local file = io.open(path, "rb")
if not file then
fileInfo.text = "data.db Not found."
return false
end
local size = file:seek("end") -- get file size
fileInfo.text = "data.db found with size of size: " .. size
return true
end
if not checkDBFile() then
createDB()
fileInfo.text = "Created new data.db."
end
-- read db content
local db = sqlite3.open( path )
for row in db:nrows("SELECT * FROM test") do
local t = display.newText( row.content, 20, 50*row.id, nil, 16 )
t:setFillColor( 1, 0, 1 )
end