Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

android - Do I need to call getWritableDatabase() everytime I manipulate data

I have a newbie question about sqlite databases in android:

Do I really need to retrieve a writeable database everytime I manipulate data?

So can I write a DAO like this:

class Dao {

        private final SQLiteDatabase database;

        public Dao(SQLiteOpenHelper databaseHelper){

             database = databaseHelper.getWritableDatabase();
    }

    public void insert(...){

       ContentValues cv = new ContentValues(4);
       database.insertOrThrow(TABLE, null, cv);
       ...
    }


    public void update(...){
        ContentValues cv = new ContentValues(4);
        database.update(....);
    }
}

or do I must write my dao like this:

class Dao {

        private final SQLiteOpenHelper databaseHelper;

        public Dao(SQLiteOpenHelper databaseHelper){

             this.databaseHelper = databaseHelper
    }

    public void insert(...){

       SQLiteDatabase database = databaseHelper.getWritableDatabase();
       ContentValues cv = new ContentValues(4);
       database.insertOrThrow(TABLE, null, cv);
       ...
    }


    public void update(...){
        SQLiteDatabase database = databaseHelper.getWritableDatabase();
        ContentValues cv = new ContentValues(4);
        database.update(....);
    }
}

If the second approach is the correct one: do I also need to close the database after every operation:

public void update(...){
    SQLiteDatabase database = databaseHelper.getWritableDatabase();
    ContentValues cv = new ContentValues(4);
    database.update(....);
    database.close();
}

I guess its the same for databaseHelper.getReadableDatabase() right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should close every cursor you open. But the database instance doesn't need to be closed after each use.

I usually fetch a writable database in onCreate() and store the resulting SQLiteDatabase as a member variable for each activity, and never explicitly close that instance. (But again, I do close every cursor as soon as I'm finished processing their results.)

See Managing SQLite Connections in Android for a little more discussion on the subject.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...