Sqlite实现增删改查

前端之家收集整理的这篇文章主要介绍了Sqlite实现增删改查前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

静态Helper类,用于建立、更新和打开数据库
private static class DBOpenHelper extends sqliteOpenHelper {

public DBOpenHelper(Context context,String name,CursorFactory factory,int version) {
super(context,name,factory,version);
}

private static final String DB_CREATE = "create table " +
DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement," +
KEY_NAME+ " text not null," + KEY_AGE+ " integer," + KEY_HEIGHT + " float);";

@Override
public void onCreate(sqliteDatabase _db) {
_db.execsql(DB_CREATE);
}

@Override
public void onUpgrade(sqliteDatabase _db,int _oldVersion,int _newVersion) {
_db.execsql("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(_db);
}
}

调用DBOpenHelper打开数据库

public void open() throws sqliteException {
dbOpenHelper = new DBOpenHelper(context,DB_NAME,null,DB_VERSION);
try {
db = dbOpenHelper.getWritableDatabase();
}
catch (sqliteException ex) {
db = dbOpenHelper.getReadableDatabase();
}
}

public long insert(People people) {
ContentValues newValues = new ContentValues();

newValues.put(KEY_NAME,people.Name);
newValues.put(KEY_AGE,people.Age);
newValues.put(KEY_HEIGHT,people.Height);

return db.insert(DB_TABLE,newValues);
}

public long deleteAllData() {
return db.delete(DB_TABLE,null);
}

public long deleteOneData(long id) {
return db.delete(DB_TABLE,KEY_ID + "=" + id,null);
}

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,null);
}

public People[] queryAllData() {
Cursor results = db.query(DB_TABLE,new String[] { KEY_ID,KEY_NAME,KEY_AGE,KEY_HEIGHT},
null,null);
return ConvertToPeople(results);
}

public People[] queryOneData(long id) {
Cursor results = db.query(DB_TABLE,
KEY_ID + "=" + id,null);
return ConvertToPeople(results);
}

查询结果转化为数据对象

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);
peoples[i].Name = cursor.getString(cursor.getColumnIndex(KEY_NAME));
peoples[i].Age = cursor.getInt(cursor.getColumnIndex(KEY_AGE));
peoples[i].Height = cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT));

cursor.moveToNext();
}
return peoples;
}

然后写个activity调用这些方法即可!

原文链接:https://www.f2er.com/sqlite/201852.html

猜你在找的Sqlite相关文章