Cursor用于数据库的查询读取,
主要方法:moveToFist moveToNext moveToPrevious getCount getColumnIndex
getColumnIndexOrThrow
getColumnName
getColumnNames moveToPosition getPosition
Cursor每次只读表中一行数据,读完后用moveToNext方法读下一行。
数据库转换成对象的方法如下:
private People[] ConvertToPeople(Cursor cursor){
int resultCounts = cursor.getCount();//总共的数据量
if(resultCounts == 0 || !cursor.moveToFirst()){//指针移动到第一条数据不成功
return null;
}
People[] peoples = new People[resultCounts];//
for(int i=0;i<resultCounts;i++){
peoples[i] = new People();
peoples[i].ID = cursor.getInt(0);//获取每行数据的ID
peoples[i].Name = cursor.getString(cursor.getColumnIndex(KEY_NAME));//获取对应数据行的KEY的String
peoples[i].Age = cursor.getInt(cursor.getColumnIndex(KEY_AGE));
//获取对应数据行的KEY的intpeoples[i].Height = cursor.getInt(cursor.getColumnIndex(KEY_HEIGHT));
//获取对应数据行的KEY的intcursor.moveToNext();
}
return peoples;//返回对象
}
private SQLiteDatabase db;
//数据库插入数据
public long insert(People people){
ContentValues newValue = new ContentValues();
newValue.put(KEY_NAME,people.Name);
newValue.put(KEY_AGE,people.Age);
newValue.put(KEY_HEIGHT,people.Height);
return db.insert(DB_TABLE,null,newValue);
}
//数据库删除所有数据
public long deleteAllData(){
return db.delete(DB_TABLE, null, null);
}
- //数据库删除指定id的数据
public long deleteOneData(long id){
return db.delete(DB_TABLE, KEY_ID + "="+ id,null);
}
//查询表中所有数据
public People[] queryAllData(){
Cursor results = db.query(DB_TABLE,new String[] { KEY_ID,KEY_NAME,KEY_AGE,KEY_HEIGHT},null,null,null,null,null);
return ConvertToPeople(results);
}
//查询表中指定id的数据
public People[] queryOneDta(long id){
Cursor results = db.query(DB_TABLE,new String[] {KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT},KEY_ID+"="+id,null,null,null,null);
return ConvertToPeople(results);
}
//更新表中数据
public long updateOneData(long id, People people){
ContentValues updateValues = new ContentValues();
updateValues.put(KEY_NAME,people.Name);
updateValues.put(KEY_AGE,people.Age);
updateValues.put(KEY_HEIGHT,people.Height);
return db.update(DB_TABLE,updateValues, KEY_ID + "=" + id,null);
}