is there a way to change my function:
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;
}
this is a raw insert, i would like to change this function to make it update or insert accordingly. i would like to change this becouse i'm already using this function in some places, but now i need to choose if insert a row or update (or ignoring the insert) a row with the same COLUMN_NOME
. can someone help me doing this?
i mean i would like to insert a new row ONLY if there isn't another with the same name (as usual you know).
Update a database When you need to modify a subset of your database values, use the update() method. Updating the table combines the ContentValues syntax of insert() with the WHERE syntax of delete() .
Introduction to SQLite UPDATE statement First, specify the table where you want to update after the UPDATE clause. Second, set new value for each column of the table in the SET clause. Third, specify rows to update using a condition in the WHERE clause. The WHERE clause is optional.
Insert: To perform insert operation using parameterized query we have to call insert function available in SQLiteDatabase class.
You can use insertWithOnConflict() if you want to insert or update, depending in whether the record exists or not:
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);
you could call int nRowsEffected = database.update(...);
if there are no rows effected by the update either the row doesn't exist (or you hosed your update()
!) therefore you need to call database.insert(...)
. of course if nRowsEffected > 0 then you are done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With