lundi 6 juillet 2015

C#: SQLite sequence of commands do not work

I created a class for managing SQLite commands to my DATA class. The class SQLiteManager look like this:

class SQLiteManager : IDisposable
{    
    protected SQLiteConnection Conn;
    protected SQLiteCommand Cmd;

    public SQLiteManager(string fullfilename)
    {
         Conn = new SQLiteConnection(string.Format("Data Source={0}", fullFileName));
         Conn.Open();
    }

    public string Query(string query)
    {
         Cmd = new SQLiteCommand(Conn);
         Cmd = Conn.CreateCommand();
         Cmd.CommandText = query;
         return Cmd.ExecuteScalar().toString();
    }

    public void Dispose()
    {
         if (Conn.State == System.Data.ConnectionState.Open)
         {
             Conn.Close();
             Conn.Dispose();
         }
         GC.SuppressFinalize(this);
    }
    ~SQLiteManager()
    {
        Conn.Dispose();
    }
}

I use this class in my form in this way:

using (SQLiteManger sqlMgr = new SQLiteManger(fileName))
{
   // .... some stuff here
   MessageBox.Show(string.format("My first query: {0}", sqlMgr.Query("....query...")); // << this works
   MessageBox.Show(string.format("My second query: {0}", sqlMgr.Query("....query...")); // << this doesnt works - NULL REFERENCE EXCEPTION comes out!
}

The second query gives a NullReferenceException even if I didn't close connection and I am into the using statement. Debugging the behaviour is as follow: At the second query the cursor comes into Query method, executes the method, but before the execution of "return Cmd.ExecuteScalar().toString();" jumps to Dispose() method.... so the exception comes out. I wonder why at the second query the program jumps to Dispose() even if I didn't require... Thank you for any suggestion. Cheers.

Aucun commentaire:

Enregistrer un commentaire