Search code examples
xamarin.androidandroid-sqlite

To close db and cannot create commands from unopened database error


    string dppath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3");
    db = new SQLiteConnection(dppath);
    string DELETEPASSCODE_DETAIL = "DELETE FROM Table1;";
    db.Execute(DELETEPASSCODE_DETAIL);
    db.Close();

Hello. When the program executes the above code and reaches the below code, I get this error: cannot create commands from unopened database

     try
            {
                string dpPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3");`
                if (dpPath.IndexOf("user.db3") < 0)
                {
                    CreateDB();
                    CreateTable();
                }
                else
                {
                    if (db == null)
                    {
                        db = new SQLiteConnection(dpPath);
                    }
                    var tableExist = db.GetTableInfo("Table1");
……

The error occurs on this db.GetTableInfo("Table1");


Solution

  • I made some mistakes for the first check of the code. Now, I reproduced this issue.

    enter image description here

    The db can not be null, delete the If statement.

    Change:

     if (db == null)
                {
                    db = new SQLiteConnection(_databasePath);
                }                
                var tableExist = db.GetTableInfo("Info");
                var table_Info = db.Table<Info>().ToList();
    

    To:

        db = new SQLiteConnection(_databasePath);
                var tableExist = db.GetTableInfo("Info");
                var table_Info = db.Table<Info>().ToList();
    

    db.Table<Info>().ToList() could also be used to get the table information.