SQLiteOpenHelper static methods best practice
I have a class extending SQLiteOpenHelper
to manage my database stuff. I find it rather tedious to be writing code like this to use my database(DBHelper
is the SQLiteOpenHelper
object):
DBHelper dbHelper = new DBHelper(context);
FeedResponse feedResponse = dbHelper.getFeedResponse(...);
dbHelper.close();
Is there anyth开发者_JAVA技巧ing wrong with replacing the above code with a static method and using it like this? Where might I run into trouble when implementing my database access like this?
FeedResponse feedResponse = DBHelper.getFeedResponse(context, ...);
public static FeedResponse getFeedResponse(Context context, ...) {
DBHelper dbHelper = new DBHelper(context);
FeedResponse feedResponse = dbHelper.getFeedResponse(...);
dbHelper.close();
return feedResponse;
}
public FeedResponse getFeedResponse(...) {
//returns data from database
}
Doing this really cuts down on always creating(typing out) a new instance of DBHelper
and also closes it without a fuss. It's all taken care of behind the scenes.
Your solution should work, but isn't optimal as you'll create a new DBHelper object for each database query. And the creation of an object is a expensive operation. It would be better if you reuse the DBHelper object.
Also you may have troubles using your DBHelper
from multiple threads.
精彩评论