android判断sqlite中数据库的某个表是否存在


2011-03-04 12:49 SQLite判断表是否存在 今天刚好用到sqlite来存放一些数据,但是需要检测表是否已经存在;

其实很简单,只要查看sqlite_master表中是否存在这条数据就可以知道了
SELECT count(*) FROM sqlite_master WHERE type='table' AND name='tableName'



android判断sqlite中数据库的某个表是否存在 final String CREATE_BASE_TABLE ="create table if not exists login (" + "id INTEGER PRIMARY KEY,"+ "email TEXT,"+ "password TEXT,"+ ");";

I have an android app that needs to check if there’s already a database available in the device, and if not, process some things and eventually create it.Then check if a particular table exists.

SQLiteDatabase db; db = openOrCreateDatabase("TestData.db", SQLiteDatabase.CREATE_IF_NECESSARY , null);

If database exists and table exists simply read the data from the 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(…), the sql query string has select command. If the returned cursor is null then 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 where id='"+idvar+";",null); if(cur==null){//our table doesn't exist, so we'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'll create one or take an action.}

翻译过来大致是这个意思:

有两种方法,

第一种方法是:不需要知道表是否存在,在创建表的时候加上if not exists 例:create table if not exists myTable(...) ,这样做的好处是,不需要知道表是否存在,只要每次都进行创建即可。因为里面有判断,如果表存在的时候,再执行这句不会发生重复创建表的情况。

第二种方法是:直接执行某个SQL语句,用try...catch来捕获数据库操作的异常。当异常表示数据库表不存在的时候,再进行处理。例:

try{

Cursor c = getWritableDatabase().query("select * from myTable",null );

catch(Exception e) // 或者是 SQLiteException .

{//添加处理代码,例如:创建表。

}

第二种的方法不如第一种好,原因是:第二种写起来比较麻烦,还有,如果有其它异常的时候,需要对异常来进行判别,并处理。

PS:

上面的E文中有一种方法是判断query的返回值 ,那个别想了,我在测试的时候,如果表被删除了,一到那里就崩溃,只能通过try...catch的方法。

猜你喜欢

转载自yand789.iteye.com/blog/2078612