sqliteDatabase的学习,我们应该重点掌握execsql()和rawQuery()方法。 execsql()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的sql语句。
其内部是拼凑sql语句来实现的,性能没有execsql()和rawQuery()方法好!!!
public class OtherPersonService {
private DBOpenHelper dbOpenHelper;
public OtherPersonService(Context context) {
this.dbOpenHelper = new DBOpenHelper(context);
}
public void save(Person person){
sqliteDatabase db = dbOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();//通过ContentValues对象来传入参数
values.put("name",person.getName());
db.insert("person",null,values);
}
public void update(Person person){
// update person set name =? where personid =?
sqliteDatabase db = dbOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name",person.getName());
db.update("person",values,"personid=?",new String[]{person.getId().toString()});
}
public void delete(Integer id){
sqliteDatabase db = dbOpenHelper.getWritableDatabase();
db.delete("person",new String[]{id.toString()});
}
public Person find(Integer id){
//如果只对数据进行读取,建议使用此方法
sqliteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.query("person",new String[]{"personid","name"},
"personid=?",new String[]{id.toString()},null);
//select personid,name from person where personid=? order by ... limit 3,5
if(cursor.moveToFirst()){
int personid = cursor.getInt(cursor.getColumnIndex("personid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
return new Person(personid,name);
}
return null;
}
public List<Person> getScrollData(Integer offset,Integer maxResult){
List<Person> persons = new ArrayList<Person>();
sqliteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.query("person",offset+","+ maxResult);
while(cursor.moveToNext()){
int personid = cursor.getInt(cursor.getColumnIndex("personid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
Person person = new Person(personid,name);
persons.add(person);
}
cursor.close();
return persons;
}
public long getCount() {// select count(*) from person sqliteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.query("person",new String[]{"count(*)"},null); cursor.moveToFirst(); return cursor.getLong(0); } }
原文链接:https://www.f2er.com/sqlite/202341.html