【发布时间】:2015-09-14 13:42:08
【问题描述】:
用户案例:
- 如果购物篮中已经存在,则按 ID 选择项目。
- 检查此项的编号。
- 如果商品编号 == 1,则从购物篮表中删除该商品并返回 0。
- 如果大于 1,则将其减一并更新表并返回数字--。
它没有更新我的“数字”列,而是默默地通过执行,我很无奈,也不能在这里发布任何堆栈跟踪,但我发布了我的代码片段,负责这项工作。
public int removeFromBasketasAnonymous(Long _id){
Log.d("app : ", " _id = " + _id);
int numbers = 0;
try {
database = openDatabaseInReadMode();
Cursor cursor = database.rawQuery("select * from basket where basket._id=" + _id + ";", null);
if (cursor != null) {
cursor.moveToFirst();
Log.d(APP, "GetCount = " + cursor.getCount());
if (cursor.getCount() == 1) {
//this item already present in basket
numbers = cursor.getInt(1);
Log.d(APP, " numbers = " + numbers);
Log.d(APP, "db id = " + cursor.getString(0));
String[] columns = cursor.getColumnNames();
for(String str : columns){
Log.d("APP ", " columns = "+str);
}
Log.d(APP, " id = " + _id);
if (numbers == 1) {
//remove this row entry
cursor.close();
database.close();
database = openDatabaseInReadWriteMode();
database.beginTransaction();
String strSQL = "DELETE from basket where basket._id=" + _id;
try{
database.execSQL(strSQL);
}catch(Exception e){
e.printStackTrace();
}finally{
database.endTransaction();
database.close();
}
numbers--;
} else {
//decrement this number by one
Log.d(APP, " number " + numbers);
numbers--;
Log.d(APP, " dcremented numbers = " + numbers);
cursor.close();
database.close();
database = openDatabaseInReadWriteMode();
database.beginTransaction();
try{
ContentValues data = new ContentValues();
data.put("numbers", numbers);
database.update("basket", data, "_id = " + _id, null);
}catch (Exception e){
e.printStackTrace();
}finally {
database.endTransaction();
database.close();
}
}
}
}
}finally{
if(database != null){
database.close();
}
}
return numbers;
}
public SQLiteDatabase openDatabaseInReadMode() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!isDataBaseExist()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
/*Log.d("DB available", "path = " + dbFile.exists() + " path" + dbFile.getPath());*/
/*Log.d("actual path ", "exists = " + isDataBaseExist());*/
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
public SQLiteDatabase openDatabaseInReadWriteMode() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!isDataBaseExist()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
/*Log.d("DB available", "path = " + dbFile.exists() + " path" + dbFile.getPath());*/
/*Log.d("actual path ", "exists = " + isDataBaseExist());*/
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
}
问候, 沙申克
【问题讨论】:
-
为什么你不能发布堆栈跟踪?
-
这对我有帮助吗? stackoverflow.com/questions/5987863/… 但我也这样做了..
-
@Opiatefuchs ,它默默地通过代码和数字列没有更新..当我再次运行相同的代码时,数字仍然和以前一样。
-
这个问题可能有很多原因,这就是为什么查看堆栈跟踪很重要。
-
在更新语句后尝试使用
database.setTransactionSuccessful();
标签: android database sqlite transactions