升级SQlite表的难度

Php*_*ete 13 sqlite android alter

我有一个运行一个名为ANIMAL的工作表的应用程序.首次创建此表时,它只包含_id和animal_name列.

现在我正在努力扩展它,包括一个animal_biography专栏,但是我有一点困难.首先我认为我只是升级我的CREATE_TABLE语句以包含动物生物:

private static final String DATABASE_CREATE = 



            "create table " + ANIMALS_TABLE +

            " (_id integer primary key autoincrement, " + 

            "animal_name text not null, " +

            "biography text not null);"; 
Run Code Online (Sandbox Code Playgroud)

然而,看着logcat它告诉我当试图插入时,列传记不存在.

现在,我尝试使用onUpgrade()包括代码来升级数据库

db.execSQL("ALTER TABLE" + DATABASE_NAME);
db.execSQL(DATABASE_CREATE);
Run Code Online (Sandbox Code Playgroud)

但这也没有解决问题.有没有人有任何关于如何解决这个问题的指示?

GrA*_*And 53

如果您使用SQLiteOpenHelper它很容易升级表.您需要实现方法onCreateonUpgrade在类构造函数中提供数据库的当前版本.当更新表只是增量数据库的版本号,在指定新创建表的查询onCreate方法,把ALTER TABLEonUpgrade的方法来更新表的早期版本.当Android检测到数据库版本不匹配时,它会onUpgrade自动调用方法.看例子:

public class OpenHelper extends SQLiteOpenHelper {

    private final static int    DB_VERSION = 2;

    public TracksDB(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        final String CREATE_TBL =
            "create table " + ANIMALS_TABLE +
            " (_id integer primary key autoincrement, " + 
            "animal_name text not null, " +
            "biography text not null);";
             db.execSQL(CREATE_TBL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < 2) {
            final String ALTER_TBL = 
                "ALTER TABLE " + ANIMALS_TABLE +
                " ADD COLUMN biography text not null;";
            db.execSQL(ALTER_TBL);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这种升级方法是修改表而不丢失用户数据的正确方法,尤其是在应用程序已经公开发布的情况下.