Hi in my database i have a string like "computer's" , i am fetching it from database and displaying listview, when i click on the list item it should store to one of my database table. I am doing it as below but it is getting crashed
public void updateFav(String key, int value) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
C_FAV=C_FAV.replaceAll("'","''");
values.put(C_FAV, value);
db.update(tableName, values, C_KEY + "='" + key.trim() + "'", null);
db.close();
}
Below is my trace
12-12 17:55:49.291: E/AndroidRuntime(18184): android.database.sqlite.SQLiteException: near "s":
syntax error (code 1): , while compiling: UPDATE fav SET favorite=? WHERE key='computer's'
You're escaping the apostrophes in C_FAV which seems to be a column name but not in key.
Consider using ? placeholder and bind arguments instead, e.g.
db.update(tableName, values, C_KEY + "=?", new String[] { key.trim() });
Related
As my title question, I want to delete some rows of table on SQLite where contains specific string.
Here are my methods I tried but there are no any row is deleted. I checked table of SQLite database by get it out and put in to DB Browser for SQLite which is downloaded from https://sqlitebrowser.org/
public void delete1(String table,String COLUMN,String link) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%");
}
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table, "PRODUCTNAME" + "LIKE ?", new String[]{name+"%"}) ;
}
Could you tell me how to do it or how have i to correct code ?
using db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{name+"%"}) ; will only delete rows that start with the value in name.
Perhpas you want :-
db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) ;
Then it would delete rows that contain the value rather than start with the value.
With db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%"); you need to enclose the string in single quotes and assuming that you want to delete a row that contains the value then use :-
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE '%"+link+"%'");
Using the delete convenience method (the first part) is the better option as it protects against SQL Injection, it properly encloses the value, builds the underlying SQL and also returns the number of affected (deleted) rows.
If you use the following, this will write dome debugging information that may assist in debugging :-
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
Log.d("DELETEINFO","Attempting to delete rows with \n\t->" + name);
int deletedCount = db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) >0) ;
Log.d("DELETEINFO","Deleted " + deletedCount + " rows.");
}
I know it's been asked a million times but I still cannot get it to work. I'm trying to delete a row from my sqlite database but I keep getting an error. I'm sure it's to do with my syntax but I cannot get the correct syntax.
heres my delete method
public void deleteRouteNote(int notePosition){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_ROUTE_NOTE, COLUMN_NOTE + COLUMN_ROUTE_NOTE_POSITION + "where" + COLUMN_ROUTE_NOTE_POSITION + "=" + notePosition, null);
db.close();
and the error I'm getting
android.database.sqlite.SQLiteException: no such column: routeNotewhererouteNotePosition (code 1): , while compiling: DELETE FROM route_note WHERE routeNotewhererouteNotePosition=9
thanks for any help!!
EDIT:
Heres how I insert the data
/////Add route note row to table
public void addRouteNote(RouteNote routeNote){
ContentValues values = new ContentValues();
values.put(COLUMN_NOTE, routeNote.get_routeNote());
values.put(COLUMN_ROUTE_NOTE_POSITION, routeNote.get_routeNotePosition());
SQLiteDatabase db = getWritableDatabase();
db.insertWithOnConflict(TABLE_ROUTE_NOTE , null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
Try this
db.delete(TABLE_ROUTE_NOTE, COLUMN_ROUTE_NOTE_POSITION + " = " + notePosition, null)
From the docs,
table String: the table to delete from
whereClause String: the optional WHERE clause to apply when deleting. Passing null will delete all rows.
whereArgs String: You may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be
bound as Strings.
So according to this your delete clause might be something like this,
db.delete(TABLE_ROUTE_NOTE,COLUMN_ROUTE_NOTE_POSITION + "=? ,new String[]{notePosition});
Hi can anyone please help me with below error in android sqlite ? really appreciate!
Caused by: android.database.sqlite.SQLiteException: no such column: House (code 1): , while compiling: select * from category where category =House
below is part of my code in which I have inserted "House" in the table
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORY_TABLE = "CREATE TABLE category( " +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"category TEXT UNIQUE)";
db.execSQL(CREATE_CATEGORY_TABLE);
}
public void addCategory(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("category", name);
db.insert(CATEGORY_TABLE, // table
null, //nullColumnHack
cv); // key/value -> keys = column names/ values = column values
db.close();}
public List getCategory(){
List<String> list=new LinkedList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.rawQuery("select * from category where category =house" , null);
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
do {
String s = (cursor.getString(1));
list.add(s);
}while (cursor.moveToNext());
return list;
}
You need to wrap house with single quotes
db.rawQuery("select * from category where category = 'house'" , null);
In my case error was in trigger I wrote on table insert and update
I want to update the last inserted row, but I get an error:
08-20 12:08:23.091: E/AndroidRuntime(13598): android.database.sqlite.SQLiteException: near "ORDER": syntax error
(code 1): , while compiling: UPDATE REVIEW SET json=? WHERE ORDER BY
date DESC LIMIT 1
My code:
public int updateDataJSON(Review review) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_JSON, review.getJson());
return db.update(TABLE_REVIEW, values, " ORDER BY date DESC LIMIT 1", null);
}
You have to read the last date in a separate step:
db.update(..., "date = (SELECT max(date) FROM ReviewTable)", ...);
(If there are multiple rows with the same date value, this will update all of them.)
ORDER BY and such are only valid in SELECT queries, not UPDATEs.
Consider the following:
Store the last inserted row id as returned by a call to insert():
long lastInsertRowId = db.insert(...);
Use the rowid in the update like
db.update(TABLE_REVIEW, values, "ROWID=?", new String[] { String.valueOf(lastInsertRowId)2 });
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.