private static final String TABLE_NAME = "person"; public int delete(String condition) { int count = mDB.delete(TABLE_NAME, condition, null); return count; } public boolean insert(ArrayList<Person> personArray) { for (int i = 0; i < personArray.size(); i++) { // ContentValues对象 ContentValues cv = new ContentValues(); cv.put("name", personArray.get(i).name); cv.put("age", personArray.get(i).age); cv.put("height", personArray.get(i).height); cv.put("weight", personArray.get(i).weight); cv.put("company", personArray.get(i).company); long result = mDB.insert(TABLE_NAME, "", cv); // 添加成功后返回行号,失败后返回-1 if (result == -1) { return false; } } return true; } public int update(Person person, String condition) { ContentValues cv = new ContentValues(); cv.put("name", person.name); cv.put("age", person.age); cv.put("height", person.height); cv.put("weight", person.weight); cv.put("company", person.company); int count = mDB.update(TABLE_NAME, cv, condition, null); return count; }
下面是使用游标进行查询的代码例子:
public ArrayList<Person> query(String sql) { ArrayList<Person> personArray = new ArrayList<Person>(); Cursor cursor = mDB.rawQuery(sql, null); if (cursor.moveToFirst()) { for (;; cursor.moveToNext()) { Person person = new Person(); person.xuhao = cursor.getInt(0); person.name = cursor.getString(1); person.age = cursor.getInt(2); person.height = cursor.getFloat(3); person.weight = cursor.getDouble(4); person.company = cursor.getLong(5); personArray.add(person); if (cursor.isLast() == true) { break; } } } cursor.close(); return personArray; }
点此查看Android开发笔记的完整目录