thedude19
thedude19

Reputation: 2673

How to close and re-open Sqlite database?

In my app, I'm supporting the backup and restoration of the Sqlite db file.

I need to close and re-open my database connection after the restore. How can I do this?

Upvotes: 4

Views: 7218

Answers (2)

rayyildiz
rayyildiz

Reputation: 338

This code may help you.

public class DbHelper {
  private static final String DATABASE_NAME = "rayyildiz_sample.db";
  private static final int DATABASE_VERSION = 1;
  private static final String TABLE_NAME = "Test";
  private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " ( "
      + "  \"Id\" INTEGER PRIMARY KEY,"
      + "  \"Firstname\" TEXT,"
      + "  \"Lastname\" TEXT,"
      + "  \"PhoneNumber\" TEXT" + ")";
  private static final String TABLE_INSERT = "INSERT INTO " + TABLE_NAME + "(Firstname,Lastname,PhoneNumber) VALUES (?,?,?)";

  private Context context;
  private SQLiteDatabase database;
  private SQLiteStatement insertSQLiteStatement;

  public DbHelper(Context context) {
    this.context = context;
    DbOpenHelper dbOpenHelper = new DbOpenHelper(context);
    database = dbOpenHelper.getWritableDatabase();
    insertSQLiteStatement = database.compileStatement(TABLE_INSERT);
  }

  public void close(){
    database.close();
  }

  public void reopen(){
    close();
    DbOpenHelper dbOpenHelper = new DbOpenHelper(context);
    database = dbOpenHelper.getWritableDatabase();    
  }

  private static class DbOpenHelper extends SQLiteOpenHelper {
    public DbOpenHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      db.execSQL(TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
      onCreate(db);
    }
  }
}

Upvotes: 2

Romain Hippeau
Romain Hippeau

Reputation: 24375

SQLite Database class has a open and close methods.

Upvotes: 1

Related Questions