Search code examples
luacoronasdk

corona sdks - Why ain't my database updating count?


I seem to be having an issue with my database in corona sdk. I want to store the play counts every time a player plays the game. my project doesn't have a gamescene and plays only through menu.lua. I have set up a highscore database (which is separate from the other one but exactly the same) and it works fine and updates/loads data fine. My play count data base however doesn't work.

At first the play count increases by 1 when the game returns to menu again once its removed. But tries after that doesn't increase the value, it's like it has reset.

Globals.lua

M.plays = 0
--------------------------
local function setupDatabase2()
    local dbPath = system.pathForFile("appInfo.db3", system.DocumentsDirectory)
    local db = sqlite3.open( dbPath )   
    local tablesetup1 = [[ 
         CREATE TABLE played (id INTEGER PRIMARY KEY, plays); 
         INSERT INTO played VALUES (NULL, '0');  
    ]]
db:exec( tablesetup1 ) --Create it now.
db:close() --Then close the database

end
setupDatabase2()

M.loadAppInfo = function()
    local dbPath = system.pathForFile("appInfo.db3", system.DocumentsDirectory)
    local db = sqlite3.open(dbPath)
    for row in db:nrows("SELECT * FROM played WHERE id = 1") do
        M.plays = tonumber(row.plays)
    end
    db:close()
end

M.saveAppInfo = function()
    local dbPath = system.pathForFile("appInfo.db3", system.DocumentsDirectory)
    local db = sqlite3.open(dbPath)
    local update = "UPDATE played SET plays='" .. M.plays .."' WHERE id=1"
    db:exec(update)
    db:close()
end

return M

menu.lua

local utils = require("helpers.globals")
local play = 0
----------------------------------------
function scene:createScene( event )
local group = self.view

utils.loadHighscoreInfo() -- Separate db which is working fine 
utils.loadAppInfo()

function beginGame( event )
    timerSrc = timer.performWithDelay(400, createBlock, -1)
    Runtime:addEventListener("enterFrame", gameLoop)
    play = play +1
    utils.plays = play
    utils.saveAppInfo()
end

Solution

  • Your SQL statement is doing all of that. Your current sql creates a table everytime it is called. Try this:

     local tablesetup1 = [[ 
         CREATE TABLE IF NOT EXISTS played (id INTEGER PRIMARY KEY, plays); 
         INSERT INTO played VALUES (NULL, '0');]]
    

    I guess that statement is pretty much self explanatory :)