【发布时间】:2018-02-12 14:27:16
【问题描述】:
我正在读取一个包含 32000 个条目的数据库并像这样更新它们:
public void updateTable(@NotNull String title) {
Pattern pattern = Pattern.compile("<span id=\"v(.+?)\" class=\"v\">.+?</span>");
SQLiteDatabase database = dbwraper.getDatabase();
Matcher m = pattern.matcher("");
ContentValues values = new ContentValues();
String[] args = new String[]{""};
String selection = "_Id=?";
HashMap<String, Integer> map = new HashMap<>();
try (SQLiteCursor cursor = (SQLiteCursor) database.query(TABLE_NAME,
new String[]{"_Id", "Label", "Content", "AdjustmentInfo"}, null, null, null, null, "_Id ASC")) {
cursor.moveToFirst();
do {
byte[] info = cursor.getBlob(3);
args[0] = cursor.getString(0);
if (info == null) {
database.delete(TABLE_NAME, selection, args);
continue;
}
String content = process(dbwraper.getDeobfuscator(), cursor.getBlob(2));
m.reset(content);
m.matches();
log.e("m.group(1) = " + m.group(1));
String[] ids = m.group(1).split("-");
int id = Integer.parseInt(ids[0]) * 1000000 + Integer.parseInt(ids[1]) * 1000 + Integer.parseInt(ids[2]);
map.put(args[0], id);
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
}
database.beginTransaction();
for (String key : map.keySet()) {
args[0] = key;
values.clear();
values.put("_Id", map.get(key));
database.update(TABLE_NAME, values, selection, args);
}
database.setTransactionSuccessful();
database.endTransaction();
}
当光标读取最后一个条目时会出现问题。我收到此错误:
CursorWindow: Failed to read row 1411, column 3 from a CursorWindow which has 1411 rows, 4 columns.
我似乎看不出问题所在。是内存分配问题吗?还是我的数据库格式错误?
【问题讨论】:
-
使用
while (cursor.moveToNext()) {...,而不是do {...} while(...),当然删除cursor.moveToFirst(); -
好的,
DatabaseUtils#dumpCursor显示了什么?在while循环之前调用它 -
不,
while (...)和do {...不一样,首先更自然,代码更少,如果结果集为空怎么办? -
好的,然后在循环体中使用
while (cursor.moveToNext()) {...,只需在循环调用Log.d之后调用cursor.getString(0),其值为cursor.getPosition,并将其与cursor.getCount进行比较,如果可以添加@ 987654335@ 到循环体并再次运行您的代码 -
我首先删除了 AdjustmentInfo 列中所有具有空值的原始数据,然后按照@ModularSynth 建议的方式进行查询 database.execSQL("DELETE FROM " + TABLE_NAME + " WHERE AdjustmentInfo IS NULL");
标签: android sqlite android-sqlite android-cursor