Cannot open SQLite database

B. Clay Shannon picture B. Clay Shannon · Dec 20, 2012 · Viewed 8k times · Source

Using this code:

public void InsertPlatypiRequestedRecord(string PlatypusId, string PlatypusName, DateTime invitationSentLocal)
{
    var db = new SQLiteConnection(SQLitePath);
    {
        db.CreateTable<PlatypiRequested>();
        db.RunInTransaction(() =>
            {
                db.Insert(new PlatypiRequested
                              {
                                  PlatypusId = PlatypusId,
                                  PlatypusName = PlatypusName,
                                  InvitationSentLocal = invitationSentLocal
                              });
                db.Dispose();
            });
    }
}

...I get, "SQLite.SQLiteException was unhandled by user code HResult=-2146233088 Message=Cannot create commands from unopened database"

...but attempting to add a "db.Open()" doesn't work, because there is apparently no such method.

Answer

chue x picture chue x · Dec 20, 2012

You are disposing the database prematurely (inside of the transaction). It is better to wrap things up inside of a "using" statement, which will dispose of the db connection:

private void InsertPlatypiRequestedRecord(string platypusId, string platypusName, DateTime invitationSentLocal)
{
    using (var db = new SQLiteConnection(SQLitePath))
    {
        db.CreateTable<PlatypiRequested>();
        db.RunInTransaction(() =>
        {
            db.Insert(new PlatypiRequested
            {
                PlatypusId = platypusId,
                PlatypusName = platypusName,
                InvitationSentLocal = invitationSentLocal
            });
        });
    }
}