如何在Android Studio Sqlite中的数据库表中添加其他列

问题描述 投票:0回答:1

我有一个用于学生的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");
java database sqlite android-studio alter-table
1个回答
0
投票

onUpgrade要运行,您必须增加版本号,这是超级调用的第4个参数。所以你需要改变

super(context, TABLE_NAME, null, 1);

to

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 genger TEXT DEFAULT NULL");
}
  • 请注意,您还应该更改onCreate方法中的代码以包括新列,以便新安装将包括新列。
© www.soinside.com 2019 - 2024. All rights reserved.