SQLite对于数据库的操作,在android中已经对于它的增、删、改、查、取得所有的数据数以及分页操作有着自定义的方法,如下:
public void add(Person person) { SQLiteDatabase db = helper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", person.getName()); values.put("age", person.getAge()); values.put("phone", person.getPhone()); db.insert("person", "name, age, phone", values); } public void delete(Integer id){ SQLiteDatabase db = helper.getWritableDatabase(); db.delete("person", "id=?", new String[]{id.toString()}); } public void update(Person person) { SQLiteDatabase db = helper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", person.getName()); values.put("age", person.getAge()); values.put("phone", person.getPhone()); db.update("person", values, "id=?", new String[]{person.getId().toString()}); } public Person query(Integer id){ SQLiteDatabase db = helper.getWritableDatabase(); Cursor cursor = db.query("person", null, "id=?", new String[]{id.toString()}, null, null, null); if (cursor.moveToFirst()) { int personid = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); short age = cursor.getShort(cursor.getColumnIndex("age")); if(cursor != null) cursor.close(); return new Person(personid, name, phone, age); } return null; } public int getCount(){ SQLiteDatabase db = helper.getReadableDatabase(); Cursor cursor = db.query("person", new String[]{"count(*)"}, null, null, null, null, null); cursor.moveToFirst(); int count = cursor.getInt(0); if(cursor != null) cursor.close(); return count; } public List<Person> getLimitData(int offset, int maxCount) { List<Person> persons = new ArrayList<Person>(); SQLiteDatabase db = helper.getReadableDatabase(); Cursor cursor = db.query("person", null, null, null, null, null, null, offset + "," + maxCount); while(cursor.moveToNext()){ int personid = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); short age = cursor.getShort(cursor.getColumnIndex("age")); persons.add(new Person(personid, name, phone, age)); } if(cursor != null){ cursor.close(); } return persons; }