10. 某个App的开发应用过程中,在版本1时,建立了一个学生表Student(sno integer, name varchar(20), age integer);在版本2时需要对该表增加一个字段手机号码phoneNumber;在版本3时,需要增加一个课程表course(id integer, name varchar, credit integer),根据此种情况完成下面的代码: (1)版本2时的SQLiteOpenHelper类的实现; (2)编写一个方法,查询学生表中的所有数据; (3)版本3时的SQLiteOpenHelper类的实现。
时间: 2023-12-10 17:40:34 浏览: 70
(1)版本2时的SQLiteOpenHelper类的实现:
```java
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myapp.db";
private static final int DATABASE_VERSION = 2;
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// create student table in version 1
db.execSQL("CREATE TABLE Student (sno INTEGER, name VARCHAR(20), age INTEGER);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
// add phoneNumber column to student table in version 2
db.execSQL("ALTER TABLE Student ADD COLUMN phoneNumber VARCHAR(20);");
}
}
}
```
(2)编写一个方法,查询学生表中的所有数据:
```java
public List<Student> getAllStudents() {
List<Student> studentList = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query("Student", null, null, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
Student student = new Student();
student.setSno(cursor.getInt(cursor.getColumnIndex("sno")));
student.setName(cursor.getString(cursor.getColumnIndex("name")));
student.setAge(cursor.getInt(cursor.getColumnIndex("age")));
student.setPhoneNumber(cursor.getString(cursor.getColumnIndex("phoneNumber")));
studentList.add(student);
}
cursor.close();
}
db.close();
return studentList;
}
```
(3)版本3时的SQLiteOpenHelper类的实现:
```java
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myapp.db";
private static final int DATABASE_VERSION = 3;
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// create student table in version 1
db.execSQL("CREATE TABLE Student (sno INTEGER, name VARCHAR(20), age INTEGER, phoneNumber VARCHAR(20));");
// create course table in version 3
db.execSQL("CREATE TABLE Course (id INTEGER, name VARCHAR(20), credit INTEGER);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
// add phoneNumber column to student table in version 2
db.execSQL("ALTER TABLE Student ADD COLUMN phoneNumber VARCHAR(20);");
}
if (oldVersion < 3) {
// create course table in version 3
db.execSQL("CREATE TABLE Course (id INTEGER, name VARCHAR(20), credit INTEGER);");
}
}
}
```
阅读全文