[英]SQLite Database Android, check if a record exists and save
我有一个扩展了SQLiteOnHelper的应用程序的数据库。然后,我必须确保,例如,如果仅更改title ,则应该更新记录,否则可以正常插入。
这是我的桌子:
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE vasca(" +
"_id INTEGER PRIMARY KEY,"+
"titoloNota TEXT NOT NULL,"+
"testoNota TEXT NOT NULL,"+
"dataNota DATE,"+
"coloreNota INTEGER NOT NULL,"+
"UNIQUE(id, titoloNota)"+ // to be reviewed
")";
db.execSQL(sql);
}
还有我的boolean插入方法:
public boolean insertNote(Nota nota){
// boolean inizializzat a false utilizzata come return
boolean resultInsert = false;
// repository dei dati in modalità scrittura
SQLiteDatabase dbLite = this.getWritableDatabase();
// utilizza un ContentValues come mappa di valori, dove le columns rappresentano le chiavi
ContentValues values = new ContentValues();
values.put(SQL_INSERT_OR_REPLACE, true);
values.put("titoloNota", nota.getTitolo());
values.put("testoNota", nota.getTesto());
values.put("dataNota", nota.getData()); // ritorna una string sdf.format(nota.getData())
values.put("coloreNota", nota.getColore());
// chiama il metodo insert su dbLite, Vasca è il nome della tabella
// poichè ritorna un long, se negativo significa che l'inserimento non è riuscito
long idInserimento = dbLite.insert("vasca", null, values);
// sfrutto la variabile long per fare un controllo se andato tutto ok
if( idInserimento <= -1 ){
Log.e(TAG, "Inserimento della nota non avvento");
resultInsert = false;
}else{
resultInsert = true;
// inserisce la nota passata al metodo nell'arrayList listNote chiamando il metodo add
}
dbLite.close();
return resultInsert;
}
我认为我们需要进行查询。 任何帮助或建议,表示赞赏:)
如果可以在内存中进行此检查,则应避免查询数据库。 编写一些将注释与用户编辑进行比较的方法。
如果没有,则可以查询数据库以获取具有除标题之外的所有相同字段的条目:
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
"_id",
"titoloNota"
};
// Define 'where' part of query.
String selection = "_id = ? AND testoNota = ? AND dataNota = ? AND coloreNota = ?";
// Specify arguments in placeholder order.
String[] selectionArgs = { nota.getId(), nota.getTesto(), nota.getData(), nota.getColore() };
Cursor c = db.query(
"vasca", // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
if (c.moveToFirst()) {
// entry with the specified selection was found
int title = c.getString(c.getColumnIndex("titoloNota"));
// UPDATE if title changed
} else {
// no entry found - INSERT
}
您应该创建一个单独的更新记录方法,或者基于标志创建单独的更新查询,该标志可以根据填写的表单已更新还是仅空白表单已打开的条件来设置。 如果要打开包含填充数据的相同表单以及空白表单,则可以通过逐个检查每个字段来检查打开的表单是空白还是填充。 如果打开了空白表单,则可以放置flag =“ insert”并触发插入查询/方法,或者如果填充的表单已更新并且用户更改了该表单中的某些内容(可以通过比较以前的值进行检查),则可以输入flag =“ update”并使用相同的方法触发相关的更新查询,或者您可以调用单独的更新方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.