connecting to two different sqlite databases in lua using luasql

361 Views Asked by At

Goal

I'm trying to connect to two different databases, one after the other. I know the first connection is working because I attempt to create a new record, and it works. When I try to connect to the second database and query a table, the logic fails with an error saying that the table I'm querying doesn't exist. But i know it does.

Here's the test code that creates the connection objects:

local database1con 
local database2con
local database1env
local database2env

local firstdatabase_connect = function()
   if not database1con then
      database1env = assert (luasql.sqlite3())
      database1con = assert (database1env:connect("database1.sqlite"))
      return true
   else
      return false 
   end
end

local seconddatabase_connect = function()
   if not database2con then
      database2env = assert (luasql.sqlite3())
      database2con = assert (database2env:connect("database2.sqlite"))
      return true
   else
      return false 
   end
end


local firstdatabase_disconnect = function()
    if database1env then
        database1env:close()
        database1env = nil
    end
    if database1con then
        database1con:close()
        database1con = nil
    end
end

local seconddatabase_disconnect = function()
    if database2env then
        database2env:close()
        database2env = nil
    end
    if database2con then
        database2con:close()
        database2con = nil
    end
end

And here's the logic that tries to actually connect to the databases:

local connected = firstdatabase_connect()
-- run some select & insert commands
firstdatabase_disconnect()

-- now connect to second database
sql = "INSERT INTO users VALUES("..user_id..", "..username.value..", 'test',"..os.date("%Y%m%d%H%M%S")..", Null,Null)"

local db2connected = seconddatabase_connect()
if db2connected then
    local res, err = database2con:execute(sql)
    if not res and err then
        success = false
    end
    seconddatabase_disconnect()
end

Problem

The insert fails with the following message: LuaSQL: no such table: users The users tables doesn't exist in database1, but does exist in database2.

What i've tested so far

I thought that perhaps even though I'm disconnecting from the first database, it was somehow checking the wrong db. So after I make the call to firstdatabase_disconnect(), I added another select statement that attempted to select from the first database.
The system failed with a message that the connection object for database1 is nil. which is good.

I'm not sure what else to test. If you have any suggestions, I'd appreciate it.

0

There are 0 best solutions below