13

我有一个使用名为 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);"; 

但是,查看 logcat 时,它告诉我列传记在尝试插入时不存在。

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

db.execSQL("ALTER TABLE" + DATABASE_NAME);
db.execSQL(DATABASE_CREATE);

但这也不能解决问题。有没有人对如何解决这个问题有任何指示?

4

1 回答 1

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);
        }
    }
}

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

于 2011-04-16T17:10:50.243 回答