开发者

Android: SQLite Database. Do we need to create it?

开发者 https://www.devze.com 2023-03-19 13:17 出处:网络
I\'ve been going through some tutorials on working with sqlite databases and they all seem to create a new database, tables, etc on the first run of the application. Is this necessary? What if I alrea

I've been going through some tutorials on working with sqlite databases and they all seem to create a new database, tables, etc on the first run of the application. Is this necessary? What if I already have a pre-built database sitting in the assets folder when the application is installed? Can I not simply just open the connection to开发者_如何转开发 said database and start using its information or is there a specific reason everyone wants to create it using sql on first launch?


This question comes up frequently. Try this tutorial to use an existing database on Android: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/


  1. You can't use database file which sits in assets folder directly as SQLite database, since this file would not be usual file located in common filesystem. E.g. you can have only readonly access to it. So the only your option is to copy those database from assets folder to device's filesystem.
  2. To handle database creation for the first time and accessing it there's special helper class SQLiteOpenHelper. Read about it here. Specifically look in SQLiteOpenHelper.onCreate() - where should sit database creation (or copying from assets folder as in your case)


It's been quite sometime since I last worked with SQLite databases (in Android) but I believe that when they write CREATE statements, they always do so with the IF NOT EXISTS condition (i.e., CREATE (DATABASE|TABLE) IF NOT EXISTS...).

I don't know what you'll use SQLite for but I believe they do that in Android "just to make sure". That is, if it's the user's first time to run the app, the DB/Tables must be created first else app goes bonkers. Otherwise, they are (probably) created already and this case will be handled by the IF NOT EXISTS clause and they just go ahead and create a connection with the existing DB. Win-win.

(If, for some reason, it is not the user's first time to use the app and the DB isn't there, it will just be created again. But that's obvious isn't it? ;) )


If you just link with preexisting database it wont bind to your system. So there may be failures. Creating db at first run is the most appropriate way to work with db.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号