我正在重构我的代码并将所有insert
语句替换为insert or replace
while 我发现使用以下方法db.insert()
而不是准备好的语句:
public static void insertIntoTableByNameAndFieldsAndValues(
String tableName, String[] fields, String[] values, Context c)
throws FieldsAndValuesMismatchException, UnrecognizedTypeException {
DatabaseAbstractionLayer dal = new DatabaseAbstractionLayer(c);
SQLiteDatabase db = dal.getWritableDatabase();
ContentValues con = new ContentValues();
if (fields.length != values.length)
throw new FieldsAndValuesMismatchException(
"fieldsString and values are not the same size");
int fieldCount = fields.length;
for (int i = 0; i < fieldCount; i++) {
String[] fieldArr = fields[i].split(":");
String value = values[i];
if (fieldArr[1].equalsIgnoreCase("long")) {
// long
if(value.equalsIgnoreCase("null")){
con.putNull(fieldArr[0]);
}else{
con.put(fieldArr[0],(long) Integer.parseInt(value));
}
} else if (fieldArr[1].equalsIgnoreCase("string") || fieldArr[1].equalsIgnoreCase("text")) {
// string
if(value.equalsIgnoreCase("null")){
con.putNull(fieldArr[0]);
}else{
con.put(fieldArr[0], value);
}
}else if(fieldArr[1].equalsIgnoreCase("double")){
//double
if(value.equalsIgnoreCase("null")){
con.putNull(fieldArr[0]);
}else{
con.put(fieldArr[0], Double.valueOf(value));
}
} else {
throw new UnrecognizedTypeException(fieldArr[1]
+ " is not string,text, long or double");
}
}
db.insert(tableName, null, con);
db.close();
}
我不想重写代码并使用原始查询。发生冲突时有没有办法替换一行?我想insertWithOnConflict()
会这样做,但我找不到一个很好的例子。