zoukankan      html  css  js  c++  java
  • SQLite添加新的字段

    通过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 ;
    }
    View Code
  • 相关阅读:
    动画效果开关
    学习网站
    html5标签 H5标签
    Bootstrap
    【CSP-S 2019模拟】题解
    【CSP-S 2019模拟】题解
    【LOJ #3095】【SNOI2019】—字符串(模拟)
    【LOJ #3095】【SNOI2019】—字符串(模拟)
    【LOJ #3084】【GXOI / GZOI2019】—宝牌一大堆(DP)
    【LOJ #3084】【GXOI / GZOI2019】—宝牌一大堆(DP)
  • 原文地址:https://www.cnblogs.com/tianciliangen/p/9431109.html
Copyright © 2011-2022 走看看