【发布时间】:2014-06-15 18:12:57
【问题描述】:
我可以使用 corona SDK 模拟器查询 SQLlite 数据库中的数据,但不能插入或删除数据。我正在运行 Corona SDK 的最新公开版本。这是代码。它编译得很好,但插入命令根本不起作用。这是main.lua的代码:
local sqlite3 = require "sqlite3"
local function setUpDatabase(dbName)
local path = system.pathForFile( dbName, system.DocumentsDirectory )
local file = io.open( path, "r" )
if ( file == nil ) then
-- copy the database file if doesn't exist
local pathSource = system.pathForFile( dbName, system.ResourceDirectory )
local fileSource = io.open( pathSource, "r" )
local contentsSource = fileSource:read( "*a" )
local pathDest = system.pathForFile( dbName, system.DocumentsDirectory )
local fileDest = io.open( pathDest, "w" )
fileDest:write( contentsSource )
io.close( fileSource )
io.close( fileDest )
end
local gameDB = system.pathForFile(dbName, system.DocumentsDirectory)
local dbNew = sqlite3.open( gameDB )
return dbNew
end
function loadData()
local sql = "select * from projects"
local projects = {}
for a in db:nrows(sql) do
projects[#projects+1] =
{
id = a.id,
name = a.name,
category = a.category,
rating = a.rating
}
end
return projects
end
function insertData(n, c, r)
local sql = "insert into projects (name, category, rating) values ('" .. n .. "', '" .. c .. "', " .. r .. ")"
db:exec(sql)
end
function deleteData(id)
local sql = "delete from projects where id = " .. tostring(id)
db:exec(sql)
end
function updateData(id, col, v)
local sql = "update projects set " .. col .. " = '" .. v .. "' where id = " .. tostring(id)
db:exec(sql)
end
db = setUpDatabase("mydatabase.sqlite")
insertData("Horse Crazy", "Game", 2)
deleteData(3)
--updateData(4, "name", "Ralph")
--updateData(4, "category", "Dog")
--updateData(4, "rating", 4)
local data = loadData()
for x = 1, #data do
print (data[x].id, data[x].name, data[x].category, data[x].rating)
end
【问题讨论】:
-
它对我来说很好用。我没有改变任何东西。我在 DocumentsDirectory 中创建了一个“mydatabase.sqlite”数据库,其中包含一个“项目”表,其中包含(id INTEGER PRIMARY KEY,名称 TEXT,类别 TEXT,评级 INTEGER)。有时对我有用的是隔离问题,创建一个干净的 main.lua 项目并在那里测试它,如果它有效,那么问题来自其他地方。希望对您有所帮助!
-
您使用的是什么版本的 Corona SDK 模拟器。我觉得它们在某种程度上是资源目录所在的问题,而插入、更新和删除语句没有找到数据库。想知道这是否与在 Windows XP Pro 64 位上运行 SDK 有关。我会在另一台电脑上试试。如果有人有其他想法,请告诉我。很高兴知道代码正在运行! - 谢谢!
标签: sqlite insert lua coronasdk