版权声明:本文为博主原创文章,未经博主允许不得转载。
通过alter添加新的字段SQL语句
"ALTER TABLE 'DiHKChatMessage' ADD 'phoneNum' varchar";
但是如果这个字段已经存在的话,运行程序直接会崩溃,那怎么解决?
我们可以在添加字段之前,对数据库进行判断看是否已经存在该字段了,方法如下:
/**
* 方法1:检查某表列是否存在
* @param db
* @param tableName 表名
* @param columnName 列名
* @return
*/
private static 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){
LogUtil.logErrorMessage("checkColumnExists1..." + e.getMessage());
}finally{
if(null != cursor && !cursor.isClosed()){
cursor.close() ;
}
}
return result ;
}
/**
* 方法2:检查表中某列是否存在
* @param db
* @param tableName 表名
* @param columnName 列名
* @return
*/
private static 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){
LogUtil.logErrorMessage("checkColumnExists2..." + e.getMessage());
}finally{
if(null != cursor && !cursor.isClosed()){
cursor.close() ;
}
}
return result ;
}