这里介绍一些SQLite一些基本常用的方法,参考API手册
首先需要得到一个SQLiteDatabase对象;
SQLiteDatabase db;
db = openOrCreateDatabase("data.db", Context.MODE_PRIVATE, null);
然后再在db中创建一个表;
db.execSQL("CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, date INTEGER, item TEXT, money INTEGER)");
增添数据;
//按键值保存插入数据,data为事先建立的表,表中有date,item,money三项
public void SQLiteSave(long date,String item,int money)
{
data.date = date;
data.item = item;
data.money = money;
ContentValues cv = new ContentValues();
cv.put("date", data.date);
cv.put("item", data.item);
cv.put("money", data.money);
//插入ContentValues中的数据
db.insert("data", null, cv);
}
//更新数据;先根据date,item,money找到已经存在的数据,得到主键_id,再根据_id将date替换为new_date
public void SQLiteUpdateDate(long date,String item,int money,long new_date)
{
String var_date=String.valueOf (date);
String var_money=String.valueOf (money);
ContentValues cv = new ContentValues();
cv.put("date", new_date);
Cursor c = db.rawQuery("SELECT * FROM data WHERE date = ? AND item = ? AND money = ?", new String[]{var_date,item,var_money});
while (c.moveToNext())
{
String _id = String.valueOf(c.getInt(c.getColumnIndex("_id")));
db.update("data", cv, "_id = ? ", new String[]{_id});
}
c.close();
}
//删除数据,根据date,item,money得到主键_id然后删除
public void SQLiteDelete(long date,String item,int money)
{
String var_date=String.valueOf (date);
String var_money=String.valueOf (money);
Cursor c = db.rawQuery("SELECT * FROM data WHERE date = ? AND item = ? AND money = ?", new String[]{var_date,item,var_money});
while (c.moveToNext())
{
String _id = String.valueOf(c.getInt(c.getColumnIndex("_id")));
db.delete("data", "_id = ?", new String[]{_id});
}
c.close();
}
这里只是提供一种方法