Update/replace row if same ID already exists - android

I have the below method which inserts values in my sqlite db. I'm trying to update the code to handle situations where "carid" and "sellerno" already exist in the table and if they do to replace with the new values being inserted. Any help is appreciated.
public void addListItem(String carid,String sellerno,String condition,String dat) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(carid, carid);
values.put(sellerno, sellerno);
values.put(cond, condition);
values.put(updatetime, dat);
db.insert(TABLE_CARS, null, values);
db.close();
}

There are two requirements:
SQLite needs to know that the combination of carid and sellerno must be unique for all rows in the table.
SQLite needs to know what to do when an insert or update results in a conflict (more than one row with the same combination of values for those columns).
You can do both of these at once by modifying your CREATE TABLE command as follows:
CREATE TABLE tableName (
column1 ...,
column2 ...,
...,
UNIQUE(column1, column2) ON CONFLICT REPLACE)
Now any insert/update will automatically replace the values in existing rows when the insert/update would create a conflict.
However, there may be situations where you do NOT want to replace the values in the row when there is a conflict. In those cases, you should specify the conflict algorithm in the insert/update itself (using this or this), which will override the replace algorithm specified above. Alternatively, you can leave off the ON CONFLICT REPLACE above and just use regular inserts/updates, but then you must insert/update with conflict when you want to replace.
You can read more about conflict algorithms here.

The update code is very similar to what you have now.
You have to add the new values but the same ids that you want, and then instead of the method insert(...) you use replace(...) or update(...).
db.update(TABLE_CARS, values, "_id "+"="+1, null);
// The third argument above is the where clause.
The other way would be:
db.replace(TABLE_CARS, null, values);
The rest of your code is the same. Just change the insert line.

Related

Using insertWithOnConflict for update or insert

I need to insert or update and I found the method insertWithOnConflict of the SQLiteDatabase, but I do not know how it checks if the entry already exists.
Theoretically I need a "Where" argument to check if a certain ID exists, and if so, it should replace all other columns.
This is what I have now, but I donĀ“t think that the second argument is the unique id
ContentValues args = new ContentValues();
args.put(AppDatabase.COLUMN_ID, entry.getId());
args.put(AppDatabase.COLUMN_NAME, entry.getAppname());
args.put(AppDatabase.COLUMN_URL, entry.getAppUrl());
database.insertWithOnConflict(AppDatabase.TABLE_FILELIST, COLUMN_ID, args, SQLiteDatabase.CONFLICT_REPLACE);
How can I manage this behaviour?
Make sure you have some appropriate constraint in your table, such as PRIMARY KEY or UNIQUE.
When inserting, add a value to this constrained column via ContentValues. If inserting the new row would violate some constraint, the conflicting rows are first deleted and then the new row is inserted.
In your case, COLUMN_ID looks like a good candidate for PRIMARY KEY constraint. The second arg nullColumnHack with value COLUMN_ID in your code is not necessary, you can pass it as null.

How to insert data into two tables at once using SQLiteDatabase in Android?

So lets say I have this code:
SQLiteDatabase sqlDB = database.getWritableDatabase();
long iD = 0;
iD = sqlDB.insert(Table1, null, TestV);
Can I somehow rewrite this to insert into two tables instead of one? My problem is that 'values' returns 3 values from one table, and 1 value from another. Therefore, the 1 value that isn't in 'Table1' sets off an error that the column cant be found in 'Table1.' Is there a way to do this? If not then should I do two separate inserts? I am confused as how to insert data into two tables in one database (Tables are Relational: one has a foreign key).
From the documentation for INSERT in SQLite:
Note that the flowchart doesn't give you an opportunity to post into more than one table at once. SQLiteDatabase.insert() is a convenience method for using the INSERT statement.
You can simulate this using database transaction:
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
db.execSQL("insert into table1...");
db.execSQL("insert into table2...");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You may need to choose the order of the inserts if there are dependencies between the values inserted, for instance if there's a foreign key relationship: ( insert to table1 and then table2, or first insert to table2...)

SQLite insert record with _id value for two or more fields

I have a case that I would like to insert record in SQLite with database.insert(table, null, values).
TABLE t2 (_id, field1, field2)
..
val.setVal1(null);
val.setVal2(val2);
..
if(val.getVal1==null){
values.put(field1, _id);
}else{
values.put(field1, var.val1);
}
values.put(field2, var.val2);
database.insert("t2", null, values);
Is possible to do sth like this "values.put(field1, _id);"?
_id is generated at database.insert().
Note: I am looking for solution for one insert call. Insert and update row with (field1=_id) is easy.
i think i see now. you're asking if you can enter a value into a specific SQLite row _id field if it's available in your val object. Else, you want the database to automatically create a unique id for that column while inserting, like normally done. Is this correct?
To that end, i would seriously reconsider this purpose. You should never be specifying values for the _id column because it needs to be unique or else you'll get exceptions thrown. Moreover, it's only purpose is to be a unique identifier for the system, so you personally knowing this value should be of no use to you.
If you still need this functionality, i'd suggest making another field in your table (much like the _id column but not it), which you can fill with randomly generated numbers or val.getVal1 values.

Android Sqlite INSERT error when table contains only _id

I have a SQLite table that contains only the _id:
"create table rule (_id integer primary key);";
When running this set of commands:
ContentValues initialValues = new ContentValues();
mDb.insert(TABLE, null, initialValues)
I obtain the following exception:
android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO rule(null) VALUES (NULL)
The initial error occurs because ContentValues cannot be empty. Android provides a convenience parameter called nullColumnHack that allows you to pass a single column with the value null, to bypass this problem.
However this doesn't apply in my case because the row id (_id) cannot be null! Based on the syntax found in the SQLite language docs, I would like to be able to run the SQLite code:
INSERT INTO rule DEFAULT VALUES;
How can i achieve something like this using the android insert method? Or is there something I need to add to my create statement?
UPDATE: In the situation where a table contains ONLY a rowid, the proper syntax is to use INSERT INTO __ DEFAULT VALUES.
The sqlite insert method listed in android does not support DEFAULT VALUES as an option.
A bug has been filed with google and to get support for default values the following commands would need to be executed:
mDb.execSQL("INSERT INTO rule DEFAULT VALUES;");
Cursor c = mDb.rawQuery("SELECT last_insert_rowid()",null);
c.moveToFirst();
int rowid = c.getInt(0);
As stated in the accepted answer, we can get around this (and DEFAULT VALUES) by using nullHackColumn and assigning the row id (_id) to null and letting SQLite make the conversion from null to the auto-incremented value.
As jeet mentioned you can provide nullColumnHack as a second parameter. And as you yourself mentioned autoincrement isn't necessary to increment a value of primary key.
So the syntax:
insert into rule (_id) values(null)
where _id is primary key and autoincremented value is correct for sql. I think most SQL databases will replace null with new incremented value, at least MySQL, SQLite and Oracle can do this
Thus:
ContentValues cv = new ContentValues();
db.insert("rule", "_id", cv);
should give you desired results.
You need to add autoincrement to your create table query like:
"create table rule (_id integer primary key autoincrement);";
In your case you need to manually set the ID of the row with each insert. this way it will increment it automatically when you insert an empty row as you did in your case.
Try this way :
ContentValues initialValues= new ContentValues();
if(check here --id is null----)
{
initialValues.put("_id", "0");
}
else
{
initialValues.put("_id", id);
}
mDb.insert(TABLE, null, initialValues)
Check following:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String, java.lang.String, android.content.ContentValues)
SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided values is empty, no column names are known and an empty row can't be inserted. If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values is empty.
the insert needs a null value you just have to put
db.insert ("people", null, c);

Is it possible to apply key's (Primary key, candidate key etc) in android while using database

I am new to android and i have just learned how to use the database and i have a couple of questions:
How can we apply keys on the data in the database in android just like we give in Oracle database? Is it possible? If no please tell me why.
When i am deleting the first row in a database (Whose id is '1') the below rows id's are not coming in serial number i.e., id for the second row (Now first row) is '2' why not '1'.
Thank you
ok, from first,
"How can we apply keys on the data in the database in android just like we give in Oracle database? Is it possible? If no please tell me why."
Ans - We can apply the all rule which one applies to a any other database, like oracle, mysql etc... So you can have both concept of primary key and foreign key in Android's SQLite database.
2.When i am deleting the first row in a database (Whose id is '1') the below rows id's are not coming in serial number i.e., id for the second row (Now first row) is '2' why not '1'?
Ans : as per the database rules whenever you delete any records from row then its key is remains same, its not changed and whatever data after that records are also has a same key or ID so whenever you want to access that data the ID or key remain same.
EDIT: and If you want to modify that key or ID you can use UPDATE query for that.
EDIT: update(String table, ContentValues values, String whereClause, String[] whereArgs)
Updating Values
To execute an update statement, we have two ways:
1. To execute db.execSQL
2. To execute db.update method:
public int UpdateEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colName, emp.getName());
cv.put(colAge, emp.getAge());
cv.put(colDept, emp.getDept());
return db.update(employeeTable, cv, colID+"=?",
new String []{String.valueOf(emp.getID())});
}
The update method has the following parameters:
1. String Table: The table to update a value in
2. ContentValues cv: The content values object that has the new values
3. String where clause: The WHERE clause to specify which record to update
4. String[] args: The arguments of the WHERE clause
Convenience method for updating rows in the database.
Hope you will understand it.
Thanks,

Categories

Resources