Android 判斷SQLite資料庫中是否存在某一個表格
final String CREATE_BASE_TABLE ="create table if not existslogin (" + "id INTEGER PRIMARY KEY,"+ "email TEXT,"+ "passwordTEXT,"+ ");";
I have an android app that needs to check if there’s already adatabase available in the device, and if not, process some thingsand eventually create it.Then check if a particular tableexists.
SQLiteDatabase db; db = openOrCreateDatabase("TestData.db",SQLiteDatabase.CREATE_IF_NECESSARY , null);
If database exists and table exists simply read the data fromthe database if the data does exist.
Tip: For checking if a table Exists:
However, It is easy to find if a table exists or NOT,
Create a SQLiteDatabase object and have a call to query(…), thesql query string has select command. If the returned cursor is nullthen the table doesn’t exist.
SQLiteDatabase tempDatabase; try {tempDatabase=SQLiteDatabase.openDatabase(DBPATH+DBNAME, null,SQLiteDatabase.OPEN_READONLY);try{Cursor cur;cur=tempDatabase.rawQuery("select * from table whereid='"+idvar+";",null); if(cur==null){//our table doesn't exist, sowe'll create one or take an action.} }catch (SQLiteException e) {//our table doesn't exist, so we'll create one or take an action.}}catch (SQLiteException e) { //our database doesn't exist, so we'llcreate one or take an action.}
翻譯過來大致是這個意思:
有兩種方法,
第一種方法是:不需要知道表是否存在,在建立表的時候加上if not exists 例:create table if notexists myTable(...),這樣做的好處是,不需要知道表是否存在,只要每次都進行建立即可。因為裡面有判斷,如果表存在的時候,再執行這句不會發生重複建立表的情況。
第二種方法是:直接執行某個SQL語句,用try...catch來捕獲資料庫操作的異常。當異常表示資料庫表不存在的時候,再進行處理。例:
try{
Cursor c = getWritableDatabase().query("select * frommyTable",null );
catch(Exception e) // 或者是 SQLiteException .
{//新增處理程式碼,例如:建立表。
}
第二種的方法不如第一種好,原因是:第二種寫起來比較麻煩,還有,如果有其它異常的時候,需要對異常來進行判別,並處理。
PS:
上面的E文中有一種方法是判斷query的返回值,那個別想了,我在測試的時候,如果表被刪除了,一到那裡就崩潰,只能通過try...catch的方法。