Sqlite Insert or Update - android

I wanted to update my existing table with new values but some of them are fresh. I have written code for updating the table, but how can I do both operations(update & insert) simultaneously.

Just use replace() method in SQLiteDatabase. Its simply insert a new row if no row with same key is not exists in database. Otherwise it replaces the existing row.. Its simple than other ways.. For more info refer the documentation..
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Try something like this:
String username="xyzName";
Cursor cur_user = my_db.rawQuery("SELECT _id from user_info where user_name ='"
+ username + "'", null);
if (cur_user.getCount() > 0) {
// User exists. Update information in database.
ContentValues cvUserInfo = new ContentValues();
cvUserInfo.put("status", status_id);
String whereClause = "user_name = '" + username + "'";
try {
my_db.update("user_info", cvUserInfo, whereClause, null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Insert the information in database.
ContentValues cvUserInfo = new ContentValues();
cvUserInfo.put("status", status_id);
cvUserInfo.put("user_name", username);
my_db.insert("user_info", null, cvUserInfo);
}
You will need to have one column except id, on which you can check. I had user name as a unique column to check for existing record.
Hope this helps.

Related

Queries in SQLite

I have the following insert statement in my app which work.
Before the insert I want to first check the database if the value name does not exist in the name column.
If it does not exists I want to continue with the insert, else display an error message.
How do I incorporate it into my existing statement below?
public void insert(HashMap<String, String> queryValues){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
Cursor c = database.query("SELECT * FROM user_details where" + "name=?", new String[] {values.put("name") });
if (c.getCount() > 0) {
// don't do it
return;
}
else {
values.put("name", queryValues.get("name"));
values.put("age", queryValues.get("age"));
database.insert("user", null, values);
}
database.close();
}
The correct way to do this is to add a unique constraint on the name field, and then use insertWithOnConflict() with a last argument of CONFLICT_FAIL. That's actually the default behavior. Your insert will fail if it would otherwise cause a constraint violation (insert() will return -1).
If you don't want to do that, there's no magic. Query your DB for a row with the given name field. If you are returned >0 rows, don't perform the insert.
Cursor c = db.query(..., "name=?", new String[] {theName}, ...);
if (c.getCount > 0) {
// don't do it
return;
}

How to prevent to insert duplicate value in sqlite database (if duplicate then overwrite)

I had created two table in my database, In both table I am inserting value at the same time, now what I want to do is that, I want to insert record in second table, but the condition is that, if there is two same record then I want insert only one record not duplicate value, In second table there is two field one is id and second is category, when user insert two same category that time I want to insert only one entry, below is my code which is not working properly, It insert all record accept duplicate value..
public long InsertCat(String idd, String cat)
{
try
{
SQLiteDatabase db;
long rows = 0;
db = this.getWritableDatabase();
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
Cursor c = db.rawQuery("SELECT * FROM " + TABLE_CATEGER + " WHERE Category='"+cat+"'",null);
while(c.moveToNext())
{
if(c.getString(0).equals(cat))
{
flag=true;
}
}
if(flag==true)
{
rows=db.update(TABLE_CATEGER, Val, "Category='"+cat+"'" , null);
System.out.print(rows);
db.close();
}
if(flag==false)
{
rows = db.insert(TABLE_CATEGER, null, Val);
System.out.print(rows);
db.close();
}
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
Put all your values inside ContentValues and then call this on writableDatabase
db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
EDIT:
Well all you need is only this part of code
SQLiteDatabase db;
long rows = 0;
db = this.getWritableDatabase();
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
rows = db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
insertWithOnConflict methods follows the last parameter as the reaction algorithm when an duplicate row is Found. And for a duplicate row to be found, the primary keys has to clash. If all this satisfys the row would surely get Replaced :-/ If not something else is going wrong..
While creating your table, put constraint on your column(Primary key or Unique key).This will not only the duplicate value to be inserted into your database.
This is working for me,and i also created Category as a primary key..
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
long rows=db.insertWithOnConflict(TABLE_CATEGER, null, Val,SQLiteDatabase.CONFLICT_REPLACE);
System.out.print(rows);
Log.d("kkkkkkkkkk",""+ rows);
db.close();
return rows; // return rows inserted.
Check with the primary key of which you want assign then while inserting check with on duplicate key..
if you want you update the row
on duplicate key update
As mentioned i am writing the code on duplicate key
INSERT OR REPLACE INTO TABLE_CATEGER(value1,value2,value3)
Use the following query
INSERT OR REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)
It will add new row if it does not exist or update row if it exists.
hope this will help you.
use insertWithOnConflict() method instead of insert()
response = sqLiteDatabase.insertWithOnConflict(TABLE_TRACKER_LOGS_LINES, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);

Android SQLite add duplicate item

I am working on sqllite. I've created the database successfully, and I can add new items to it.
// Adding new contact
public void Add_Contact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Image, contact.getImage()); // Contact image
values.put(KEY_Counter, contact.getCounter()); // Contact counter
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
This code working perfect, now I want to check if I can also save the same information, for example, if I first save "Hello Android" and in a second time try to save the same information, I want to show for example: Toast message or other.
First make a function like this:
public boolean somethingExists(String x) {
Cursor cursor = database.rawQuery("select 1 from " + TABLE_CONTACTS + " where KEY_Tittle like '%" + x
+ "%'", null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
And then before every insert call this funcition to return if it exists or not like this:
if (!somethingExists("hello world")) {
//HERE DO INSERTION if it is not already in Table e.g like call AddContact function here for insertion etc
} else {
//Display Toast message here "Record already exists"
}
p.s i just wanted to highlight the logic - your actual table names, schema & logic might be different. Anyways, try this - it should work. The actually working is supposed to follow all database constraints, structure and schema of your design.

Inserting data to SQLite table with constraint failure

Inserting data to SQLite table with constraint failure
I'm trying to insert data into SQLite table on Android. _id is primary key of the table and I am inserting a row using this method:
public void addSomeData(int id, String datetime) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, id);
contentValues.put(KEY_DATETIME, datetime);
mDb.insert(TABLE, null, contentValues);
}
The problem I get is that sometimes primary key constraint is validated and I would like to use something like INSERT IF NOT EXISTS, but preferably something that would work with ContentValues. What are my options? I understand that insertOrThrow() and insertWithOnConflict() methods only return different values, or should I use one of these methods?
Use insertWithOnConflict() with CONFLICT_IGNORE.
Will return ROWID/primary key of new or existing row, -1 on any error.
In my case "constraint failure" happened because of I had some tables which are depended on each other. As for the "insert if not exist", you can query with this id and you check if the cursor's count is bigger than zero. Check the method I'm already using in my app.
public boolean isRowExists(long rowId) {
Cursor cursor = database.query(this.tableName, this.columns, DBSQLiteHelper.COLUMN_ID + " = ? ", new String[] { "" + rowId }, null, null, null);
int numOfRows = cursor.getCount();
cursor.close();
return (numOfRows > 0) ? true : false;
}
to do so you could simply query the db to see if a row with that key exists and insert the new row only if the query returns no data.

Before inserting a record in the database to validate that there is

Before inserting a record in the database to validate that there is, for example I have a table that has two fields, table fields VA with Customer, First, I want to validate the field if there is no customer registration and if there insert
That i want to do in android using Sqlite
String sql = "SELECT * FROM TABLE WHERE id = '" + id + "'";
Cursor data = database.rawQuery(sql, null);
After this check by following code
if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}
Look at SQLite constraints. This really isn't Android-specific; it's a feature of SQLite.
Try this, it works for me.
String[] args = { myDataToCheck };
c = ourDatabase.query(DATABASE_TABLE, columns,
myColumnToCheck + "=?", args, null, null, null);
if (c.getCount() == 0) {
// doesn't exists
}else{
//exists
}
You have 2 possibilities :
1)make a select to check if there is the same key in database, then insert or update.
2)make directly an update. update will return the number of row updated, if the number is 0, so you can do an insert.

Categories

Resources