我有数据库comments.db我已经创建了一个表table_comments 我想在这个数据库中创建第二个表(table_birthday)。我的问题是如何在现有数据库中添加此表?我有以下代码。任何帮助表示赞赏。
package com.example.proj1;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
//table 1
public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
//table 2
public static final String TABLE_BIRTHDAY = "birthday";
public static final String Birthday_ID = "_id";
public static final String COLUMN_Birthday = "bday";
//database
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 1;
// table 1
private static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";
//table 2
private static final String DATABASE_CREAT = "create table "
+ TABLE_BIRTHDAY + "(" + Birthday_ID
+ " integer primary key autoincrement, " + COLUMN_Birthday
+ " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
database.execSQL(DATABASE_CREAT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),"Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BIRTHDAY);
onCreate(db);
}
}
答案 0 :(得分:2)
使用应用管理器擦除您的应用数据,或者只是卸载并重新安装您的应用。
您的测试环境已经有一个架构版本为1的数据库,当您通过添加另一个表来修改架构时,由于架构版本相同且数据库已存在,因此不会升级或创建数据库。
对于已发布的版本,您应该提升DB_VERSION
并在onUpgrade()
中实施相应的迁移代码。