gpt4 book ai didi

android - insertWithOnConflict() 与插入或替换

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:39 25 4
gpt4 key购买 nike

我正在重构我的代码并将所有 insert 语句替换为 insert or replace 而我发现以下方法使用 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() 会这样做,但我找不到一个好的例子。

最佳答案

是的,(如果您不遵循 Android 使用的行标识符的标准名称,请将 BaseColumns._ID 更改为合适的名称)这应该可以满足您的要求:

db.insertWithOnConflict(tableName, BaseColumns._ID, v, 
SQLiteDatabase.CONFLICT_REPLACE);

但是 - 这种方法确实做了很多毫无意义的事情。简而言之,它可以归结为:

public static void insertIntoTableByNameAndFieldsAndValues(
String tableName, String[] fields, String[] values, Context c)
throws FieldsAndValuesMismatchException {

if (fields.length != values.length) {
throw new FieldsAndValuesMismatchException(
"fields[] and values[] are not the same length");
}
ContentValues v = new ContentValues();
// You really don't need to distinguish between integers, doubles
// etc. etc. - SQLite is type agnostic, just dumping Strings from Java
// will work just fine - the *only* point in converting stuff is to check
// the format prior to inserts.
// Using "null" as the null identifier is also pointless. Pass actual null
// values instead - calling #putNull("somecolumn") is the same
// as #put("somecolumn", null)
for (int i = 0; i < fields.length; i++) {
v.put(fields[i], values[i]);
}
db.insertWithOnConflict(tableName, BaseColumns._ID, v,
SQLiteDatabase.CONFLICT_REPLACE);
}

关于android - insertWithOnConflict() 与插入或替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11757141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com