问题
There have been a few questions on this topic but none giving firm reasons for why there should or shouldn't be a single or multiple instances of the databaseHelper. When is it a good idea to have multiple instances of DatabaseHelper and when is it not. Is less complexity (if that is actually the case ) a good enough reason to have just a single instance ?
回答1:
Your DatabaseHelper
should be a singleton for sure. Each helper maintains the single connection to the database. If you have multiple helpers with connections to the same database, then concurrency issues will result. Sqlite does it's own locking underneath the single connection to ensure proper concurrent access to the database so using that single connection (and therefore that single helper) for all of your database operations is recommended and required.
回答2:
Use one DatabaseHelper for each database in the application. SQLite takes care of file locking for you (many reads, only one write) and Android using Java locking in SQLiteDatabase. However, you can still get have a concurrency failure (simulataneous connections writing at once). It's the multiple connnections part that you want to avoid and that is what is managed by one instance of the DatabaseHelper.
来源:https://stackoverflow.com/questions/11564348/databasehelper-singleton-or-not