SQlite raw query for insert stement - android

I need help how to implement rawquery in sqlite. I need to insert a record in to specific row in table. I searched and found that I can achieve this using raw query. I am new to sqlite and don't know how to implement raw query. I got syntax error.
Here is my code
public void insert (String potision, String total, String curent)
{
SQLiteDatabase db = this.getWritableDatabase();
db.rawQuery("INSERT INTO "+Table_Name2+" VALUES(?,?) WHERE ID = ? ", new String[] {total,curent,potision});
}
Here is my syntax error:
SQLiteException: near "WHERE": syntax error (code 1): , while compiling: INSERT INTO item_counts_2 VALUES(?,?) WHERE ID = ?
Help will be appreciated

You are having a syntax error because you added a where clause to an insert.
When you execute an insert, you are adding a row to the database. There is no sense in specifying a row.
If you were updating a row, then, the where clause would be fine, because you have to tell him what row to update.
Also when deleting rows, the where clause is widely used, so that you don't erase the whole table.
Insert: official docs
Update: official docs
Delete: official docs
Note that the docs refer to SQLite, since you are using Android.

You can use update query with ContentValues to update specific row data in your DB like this
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_1, value1);
values.put(COLUMN_2, value2);
return db.update(TABLE_NAME, values, ID + " = ?",
new String[] { String.valueOf(idValue) });
Hope it will help you out.

Don't use where clause with insert query.
If you are inserting a new row to database then where clause is redundant, remove it and it will work fine.
OR,
If you want to update value already exist in database, use update query instead of insert,
for more information visit here.

Related

Insert data into two table at once using foreign key

Database Design
Above pic shows my database design. I want to insert data into these two tables. Some part into one table and some into second table using foreign key.
Also how can i delete data from two tables at once using foreign key.
public boolean insertToBlockList(String originatingAddress,String messageBody){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ORIGINATING_ADDRESS,originatingAddress);
contentValues.put(MESSAGE_BODY, messageBody);
db.insert(TABLE_BLOCK_LIST,null,contentValues);
return true;
i wrote this code but doesn't work for me. kindly help.
how to select and show data from these two tables using foreign key?
SELECT *
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
Read more: http://www.w3schools.com/sql/sql_join_inner.asp
You have to execute two insert queries as told by #Prerak. However you have to use sql transactions for better result.

Update/replace row if same ID already exists

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.

How to update android database when fresh JSON content arieves?

Could someone suggest me a way on how to update my apps SQLite database when the content of the parsed JSON file is changed?
I am having a hard time finding the right solution, now I have to clear the cache before the app starts, but the end user obviously won't do that.
I asume changing the table version is not suitable for frequent updates (hourly).
Thanks!
As #KenWolf mentioned this documentation in the comments.
Update a Database:
When you need to modify a subset of your database values, use the update() method.
Updating the table combines the content values syntax of insert() with the where syntax of delete().
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// New value for one column
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
// Which row to update, based on the title
String selection = FeedEntry.COLUMN_NAME_TITLE + " LIKE ?";
String[] selectionArgs = { "MyTitle" };
int count = db.update(
FeedReaderDbHelper.FeedEntry.TABLE_NAME,
values,
selection,
selectionArgs);
Change your database version by incrementing by 1 from current value.
It will make possible of updation.

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...)

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);

Categories

Resources