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的方法。