我有本地sqlite数据库的android应用程序,但我有重复行的问题。每当我启动应用程序时,都会向db添加项目,但是那里已经存在一些具有相同ID的项目。问题是我无法更新/重写具有相同ID的行。这是我的db:link
声明:
// Database Name
private static final String DATABASE_NAME = "foodsDB";
// Contacts table name
private static final String TABLE_FOODS = "tableFoods";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_FOODNAME = "food_name";
private static final String KEY_ALERGEN_NO = "alergen_numbers";
private static final String KEY_DATE = "date";
private static final String KEY_FOOD_NUMBER = "food_number";
DB create table:
// Creating Table
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FOODS_TABLE = "CREATE TABLE " + TABLE_FOODS + "("
+ KEY_ID + " TEXT," + KEY_FOODNAME + " TEXT,"
+ KEY_ALERGEN_NO + " TEXT," + KEY_DATE + " TEXT," + KEY_FOOD_NUMBER + " INTEGER"+")";
db.execSQL(CREATE_FOODS_TABLE);
}
数据库插入:
// Adding new food
void addFood(FoodsDB food) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, food.getID());
values.put(KEY_FOODNAME, food.getFoodName());
values.put(KEY_ALERGEN_NO, food.getAlergenyNumbers());
values.put(KEY_DATE,food.getDate());
values.put(KEY_FOOD_NUMBER,food.getFoodNumber());
db.beginTransaction();
try {
long rowId = db.insertOrThrow(TABLE_FOODS, null, values);
if (rowId == -1) {
// insertion failed
String whereClause = KEY_DATE;
//String[] whereArgs = new String[] {values.getAsString(KEY_DATE)};
db.update(TABLE_FOODS, values, whereClause, null);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
db.close(); // Closing database connection
}
知道为什么我在DB中有更多具有相同ID的行?我也尝试将id设置为主键,但这不起作用。