android 檢測sqlite數據表是否存在html
/**
* 方法:檢查某表是否存在
*/
synchronized public boolean isTableExist(String tableName) {
boolean result = false;
if (tableName == null) {
return false;
}
SQLiteDatabase db;
Cursor cursor;
try {
db = dbHelper.getWritableDatabase();
if (db.isOpen()) {
String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + tableName.trim() + "' ";
cursor = db.rawQuery(sql, null);
if (cursor.moveToNext()) {
int count = cursor.getInt(0);
if (count > 0) {
result = true;
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
return result;
}java
android 檢測sqlite數據表中字段(列)是否存在 (轉)
android
原文摘自 http://www.tuicool.com/articles/jmmMnusql
通常數據庫升級時,須要檢測表中是否已存在相應字段(列),由於列名重複會報錯。方法有不少,下面列舉2種常見的方式:數據庫
一、根據 cursor.getColumnIndex(String columnName) 的返回值判斷,若是爲-1表示表中無此字段ui
/** * 方法1:檢查某表列是否存在 * @param db * @param tableName 表名 * @param columnName 列名 * @return*/private boolean checkColumnExist1(SQLiteDatabase db, String tableName , String columnName) { boolean result = false ; Cursor cursor = null ; try{ //查詢一行 cursor = db.rawQuery( "SELECT * FROM " + tableName + " LIMIT 0" , null ); result = cursor != null && cursor.getColumnIndex(columnName) != -1 ; }catch (Exception e){ Log.e(TAG,"checkColumnExists1..." + e.getMessage()) ; }finally{ if(null != cursor && !cursor.isClosed()){ cursor.close() ; } } return result ; }
二、經過查詢sqlite的系統表 sqlite_master 來查找相應表裏是否存在該字段,稍微換下語句也能夠查找表是否存在spa
/** * 方法2:檢查表中某列是否存在 * @param db * @param tableName 表名 * @param columnName 列名 * @return*/private boolean checkColumnExists2(SQLiteDatabase db, String tableName , String columnName) { boolean result = false ; Cursor cursor = null ; try{ cursor = db.rawQuery( "select * from sqlite_master where name = ? and sql like ?" , new String[]{tableName , "%" + columnName + "%"} ); result = null != cursor && cursor.moveToFirst() ; }catch (Exception e){ Log.e(TAG,"checkColumnExists2..." + e.getMessage()) ; }finally{ if(null != cursor && !cursor.isClosed()){ cursor.close() ; } } return result ; }