Add a new field SQL statement by alter
"ALTER TABLE ' dihkchatmessage ' ADD ' phonenum ' varchar";
But if this field already exists, the running program will crash directly, how to solve it?
Before adding a field, we can judge the database to see if the field already exists, as follows:
/**
* Method 1: Check if a table column exists
* @param db
* @param tableName table name
* @param columnName column name
* @return
*/
Private static boolean checkColumnExist1(SQLiteDatabase db, String tableName
, String columnName) {
Boolean result = false ;
Cursor cursor = null ;
Try{
/ / Query a line
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 ;
}
/**
* Method 2: Check if a column in the table exists
* @param db
* @param tableName table name
* @param columnName column name
* @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 ;
}
View Code
SQLite adds a new field