public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // String sql = "drop table if exists person"; // Log.i("TAG","我被删除了"); // onCreate(db); String sql = "alter table person add phone char(20) null"; db.execSQL(sql); }
3、数据库更新测试
首先修改版本号version的值(递增)
然后重新运行测试方法testCreateDb()
CRUD实验步骤
建立PersonService业务类
package cn.class3g.service; … public class PersonService { private DatabaseHelper dbHelper; private Context context; public PersonService(Context context) { this.context = context; dbHelper = new DatabaseHelper(context); } public void save(Person person) { SQLiteDatabase db = dbHelper.getWritableDatabase(); // String sql = "insert into person(name,age) values('Tom',21)"; // db.execSQL(sql); // 防止用户输入数据错误,如:name="T'om" String sql = "insert into person(name,age) values(?,?)"; db.execSQL(sql, new Object[] { person.getName(), person.getAge() }); } public void update(Person person, int id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String sql = "update person set name=?,age=? where personid=?"; db.execSQL(sql, new Object[] { person.getName(), person.getAge(), id }); } public Person find(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "select * from person where personid=?"; Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(id) }); if (cursor.moveToNext()) { Person person = new Person(); person.setName(cursor.getString(cursor.getColumnIndex("name"))); person.setId(cursor.getInt(0)); person.setAge(cursor.getInt(2)); cursor.close(); // 关闭游标 return person; } return null; } public void delete(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "delete from person where personid=?"; db.execSQL(sql, new Object[] { id }); } public List<Person> getScrollData(int startIdx, int count) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "select * from person limit ?,?"; Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(startIdx), String.valueOf(count) }); List<Person> list = new ArrayList<Person>(); while(cursor.moveToNext()){ Person p = new Person(); p.setId(cursor.getInt(0)); p.setName(cursor.getString(1)); p.setAge(cursor.getInt(2)); list.add(p); } cursor.close(); return list; } public long getRecordsCount() { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "select count(*) from person"; Cursor cursor = db.rawQuery(sql, null); cursor.moveToFirst(); long count = cursor.getInt(0); cursor.close(); return count; } }
在测试类cn.class3g.db. PersonServiceTest中添加对应测试方法