[英]How to add an additional column in a database table in Sqlite?
我有一個供學生使用的 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";
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);
到
super(context, TABLE_NAME, null, 2);
但是,當您的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");
}
您可能希望查看How To: Android SQLite onUpgrade()因為這將使用i和i1值,因為如果您隨后引入更多架構更改並將版本增加到 3(依此類推),您會遇到問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.