Do I need to use db:close() in every scene?

Hello. I have a quick question.

I open the same database in ~50 scenes.
sqlite3.open(path)

Do I need to add the closing db event to every scene where I open it?
db:close()

Or that’s enough to add it to only one, first scene where I open the db?

Cheers!

a good practice is to open it when starting the application and close it when exiting the application

1 Like

All my apps use databases. The orangegstudios tip is the best option. You do not need to close it in every scene. The scene change does not interfere at all in the connection with the database.

This is an example: (do this in your main.lua file)

-- myDB is global, so you can use it in any scene
_G.myDB = nil

local sqlite3 = require( "sqlite3" )

Runtime:addEventListener("system", function(event)

    if event.type == "applicationStart" then

        -- Open database
        local path = system.pathForFile( "assets/db/myData.db", system.ResourceDirectory )
        myDB = sqlite3.open( path )

    elseif event.type == "applicationExit" then
        
        -- Close database
        myDB:close()
       
    end
end)
1 Like