Java 如何在Sqlite中的数据库表中添加附加列?
我有一张学生用的SQLite表格 我想在学生中添加另一个关于学生性别的专栏。我有下面的代码来创建我的表 如何在学生表格中添加“性别”列Java 如何在Sqlite中的数据库表中添加附加列?,java,android,database,sqlite,alter-table,Java,Android,Database,Sqlite,Alter Table,我有一张学生用的SQLite表格 我想在学生中添加另一个关于学生性别的专栏。我有下面的代码来创建我的表 如何在学生表格中添加“性别”列 private static final String TAG = "SyncStudents"; //Declare tables and fields where we will store all the amdins information. private static final String TABLE_NAME = "studetns"; pr
private static final String TAG = "SyncStudents";
//Declare tables and fields where we will store all the amdins information.
private static final String TABLE_NAME = "studetns";
private static final String COL1 = "id";
private static final String COL2 = "firstname";
private static final String COL3 = "lastname";
private static final String COL4 = "age";
private static final String COL5 = "dob";
private static final String COL6 = "cir";
private static final String COL7 = "class";
private static final String COL8 = "address";
private static final String COL9 = "grade";
public SyncRoutesHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//Create the table
String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL1 + " INTEGER PRIMARY KEY, " + COL2 + " TEXT," + COL3 + " TEXT," + COL4 + " INTEGER," +
COL5 + " INTEGER," + COL6 + " INTEGER," + COL7 + " TEXT," + COL8 + " TEXT," + COL9 + " INTEGER )";
//Execute the above statement
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
db.execSQL("ALTER TABLE students ADD COLUMN genger TEXT DEFAULT NULL");
}
我试图在“OnUpdate”方法中的行下写入,但它不起作用
db.execSQL("ALTER TABLE students ADD COLUMN gender TEXT DEFAULT NULL");
要运行onUpgrade,必须增加版本号,这是超级调用的第四个参数。所以你需要改变
super(context, TABLE_NAME, null, 1);
到
但是,当您的onUpgrade方法删除表并调用onCreate时,您最好更改onCreate方法中的代码以包含新列这将删除所有现有数据。
如果需要保留现有数据,则onUpgrade方法应该只有一行代码来更改表,并且是:-
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("ALTER TABLE students ADD COLUMN gender TEXT DEFAULT NULL");
}
- 请注意,您还应该更改onCreate方法中的代码以包括新列,以便新安装将包括新列李>
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("ALTER TABLE students ADD COLUMN gender TEXT DEFAULT NULL");
}