I know there are already too many questions about this, and believe me I've done my part reading the answers to find a solution. Unfortunately, I can't find my mistake
Here's my code:
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("eat_it", 1);
values.put("expired", 1);
String[] args = {food.name, "0"};
db.update("foods", values, "name=? AND expired=?", args);
db.close();
What I want to do:
Find a record in the table foods WHERE the value of column name = food.name and the value of column expired = 0. If found, SET the record's eat_it column to 1 and expired column to 1. If no record found, don't do anything
Here's my create table syntax:
CREATE TABLE IF NOT EXISTS foods (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
...
eat_it INTEGER DEFAULT 0,
expired INTEGER DEFAULT 0
);
Here's the error message:
...
Caused by: android.database.sqlite.SQLiteException: near "WHERE": syntax error (code 1): , while compiling: UPDATE foods SET expired=?,eat_it=? WHERE name ='Taco Salad'WHERE expired = 0
...
Thanks for your help
====UPDATE====
Apparently after I restart my computer it worked. I think my emulator was not working properly/ still has the old code. Thanks everyone for helping
Error message returned per your post
near "WHERE": syntax error (code 1): , while compiling: UPDATE foods
SET expired=?,eat_it=? WHERE name ='Taco Salad'WHERE expired = 0
It's clear from the error statement that you have two WHERE clause in your query and so the error.
UPDATE foods SET expired=?,eat_it=?
WHERE name ='Taco Salad'
WHERE expired = 0 <-- Here
Your UPDATE statement should look like
UPDATE foods SET expired=?,eat_it=?
WHERE name ='Taco Salad'
AND expired = 0
You can use the where statement without using the 'whereArgs' like this:
db.update("foods", values, "name="+food.name+" AND expired=0", null);
Also, since you're updating internal values, you can also try a simple query:
db.rawquery("UPDATE foods SET eat_it=1, expired=1 WHERE name="+food.name+" AND expired=0");
Although there should be nothing wrong with what you wrote there, you can try those two options to make it work.
Related
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.
I have a sqlite db with 3 tables. TABLE1, TABLE2 and TABLE3.
I am using the following API to delete row(s) from the DB:
int rowsAffected = db.delete(tableName, "columnName=?", new String[] {String.valueOf(shoeId)});
Now, when I run this API for TABLE1 and TABLE2, the rows get deleted fine and I get the correct number in rowsAffected. But when i used this API for TABLE3, I always get rowsAffected as 0 and no entries are deleted.
int rowsAffected = db.delete(tableName, "columnName=?", new String[] {String.valueOf(shoeId)});
All 3 tables have the shoeId column.
Could someone please help?
Thanks.
The second parameter is the where clause, so you query should look like this :
int rowsAffected = db.delete(tableName, "nameOfColumn=?", new String[] {String.valueOf(shoeId)});
This means : "DELETE FROM tableName WHERE nameOfColumn = String.valueOf(shoeId)"
Don't remove the =?, it is used for prepared statements
The above query was not working due to the following reasons:
Lets say the columnName here is busTicketId and its data type is Int.
When the DB was created, the busTicketId was erroneously created as default String type due to an error in the Create table query.
As a result when the time came to delete busTicketId, it was trying to search for busTicketId, which was of Int type and since it could not find any, the rows affected count always turned out to be 0.
Once the data type issue for this column was fixed while creating the table, this issue also got fixed.
My code follows:
SELECT COUNT(_id) AS count FROM general WHERE _id = 1 CASE WHEN count > 0 THEN UPDATE general SET userGivenId = 'xxx' WHERE _id = 1 ELSE INSERT INTO general (userGivenId) VALUES ('xxx' ) END
With the error:
android.database.sqlite.SQLiteException: near "CASE": syntax error: , while compiling: SELECT COUNT(_id) AS count FROM general WHERE _id = 1 CASE WHEN count > 0 THEN UPDATE general SET userGivenId = 'xxx' WHERE _id = 1 ELSE INSERT INTO general (userGivenId) VALUES ('xxx' ) END
This is the shortest query I will use. Why I do this is because my other queries will have rows that needs to be updated but some may not be touched. Using replace will replace all the data (at least that is how it works for me on my Android phone). For instance my File class will have a filePath, but sometimes the response from the server will return null and I am only to update the File IF the server returns a new File.
Did I forget to write anything?
SQLite does not have any control logic because this would not make sense in an embedded database (there is no separate server machine/process whose asynchronous execution could improve performance).
CASE can be used only for expressions, not for entire commands.
Handle the control logic in your app:
Cursor c = db.rawQuery("SELECT 1 FROM general WHERE _id = 1", null);
if (c.moveToFirst())
db.execSQL("UPDATE general SET userGivenId = 'xxx' WHERE _id = 1");
else
db.execSQL("INSERT INTO general (userGivenId) VALUES ('xxx')");
For these particular commands, if you have a unique constraint on the _id column (and a primary key is constrained to be unique), you can use the INSERT OR REPLACE command:
INSERT OR REPLACE INTO general(_id, userGivenId) VALUES(1, 'xxx')
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);
I have a common problem, and have looked at several solutions but haven't seen one that fits this case.
I have a temporary table that is defined as follows:
public static final String GROUP_TABLE_CREATE =
"CREATE TEMP TABLE "+GROUP_TABLE_NAME+" ("
+GROUP_ID_COLUMN_NAME+" INTEGER PRIMARY KEY AUTOINCREMENT, "
+GROUP_GROUP_ID_COLUMN_NAME+" INTEGER NOT NULL UNIQUE, "
+GROUP_COLUMN_NAME+" VARCHAR(64) NOT NULL)";
The table is created without any problems. I then download some data to insert into it and use the following query to insert it:
ContentValues contentValues = new ContentValues();
contentValues.put(WhereWolfOpenHelper.GROUP_GROUP_ID_COLUMN_NAME, groupID);
contentValues.put(WhereWolfOpenHelper.GROUP_COLUMN_NAME, groupName);
db.insert(WhereWolfOpenHelper.GROUP_TABLE_NAME, null, contentValues);
And then I get the following error:
08-05 08:52:37.791: ERROR/Database(847): Error inserting group_name=Friends group_id=2
08-05 08:52:37.791: ERROR/Database(847): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
The error appears twice, and the only data in the database is the group named Friends (there should be two more entries).
I have another table with very similar code that works without any problems, so I'm guessing it's just some silly mistake that I haven't spotted. Anyone got any ideas?
If "constraint failed" than something in table scheme should tell us what is wrong.
I see what it show data what it want to insert, this means what NOT NULL constraint is OK.
In this case I've only one assumption what you already inserted some GROUP_GROUP_ID_COLUMN_NAME with value 2 and UNIQUE constraint is failed because of that.
Are you using a temporary table on purpose? A temporary table dies once the DB connection is closed. If this is the case, the table will get created and the insert will not correspond to any table. So the constraint 19 can correspond to 'Table not found'
You shouldn't pass null values in insert method. Pass empty strings.