Mat*_*yr' 6 sqlite android insert
有没有办法改变我的功能:
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
Run Code Online (Sandbox Code Playgroud)
这是一个原始插入,我想更改此功能,使其更新或插入相应.我想改变这个因为我已经在某些地方使用了这个功能,但现在我需要选择是否插入一行或更新(或忽略插入)一行具有相同的功能COLUMN_NOME.有人可以帮我这么做吗?
我的意思是我只想插入一个新行,如果没有另一个具有相同的名称(通常你知道).
len*_*ooh 33
如果要插入或更新,可以使用insertWithOnConflict(),具体取决于记录是否存在:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_VALUE, value);
// this will insert if record is new, update otherwise
db.insertWithOnConflict(TABLE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
Run Code Online (Sandbox Code Playgroud)
小智 13
您可以调用,int nRowsEffected = database.update(...);如果没有行受更新影响,则该行不存在(或者您已经冲洗了update()!)因此您需要调用database.insert(...).当然,如果nRowsEffected> 0,那么你就完成了.
您可以使用execSQL并使用INSERT OR REPLACE
String[] args = {"1", "newOrOldCategory"}; // where 1 is the category id
getWritableDatabase().execSQL("INSERT OR REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)", args);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21419 次 |
| 最近记录: |