SQLite adds a new field

Source: Internet
Author: User
Tags getmessage sqlite



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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.