So this seems pretty simple but I haven't been able to figure out what I'm doing wrong here. I have my database delete command:
public boolean deleteContact(String rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
I also should mention that I am displaying the database in a listview. So when the user clicks on an item they are presented with a "OK" and a "Delete" option.
When they hit delete this is the command I'm using:
db.open();
db.deleteContact("Apple Recipe");
db.close();
dialog.dismiss();
I keep getting a force close issue that says:
android.database.sqlite.SQLiteException: ner "Recipe":syntax error
(code 1): , while compiling: DELETE FROM list WHERE item=Apple Recipe
I'm probably doing something stupid so maybe fresh eyes will help.
Add ' in your delete statement, like this :
return db.delete(DATABASE_TABLE, KEY_ROWID + "='" + rowId + "'", null) > 0;
Or, as mentionned by other posters, you can use separate parameters :
String whereString = KEY_ROWID + "= ?";
String[] whereArgs = new String[] { rowId };
db.delete(DATABASE_TABLE, whereString, whereArgs);
the delete method for a contentResolver takes, a Uri, a "where" string, and an args string.
and row id is most likely an int
So it should be something like this
db.delete(DATABASE_TABLE,"rowId = ? ", row_id_number);
or if you are looking to match some field such as "recipe" which is a string then.
assuming the field name is recipe:
db.delete(DATABASE_TABLE, "recipe = ?", "Apple Recipe");
To be honest you should be using:
return db.delete(DATABASE_TABLE, KEY_ROWID + "=?", new String[]{rowId}) > 0;
Its more of a safety thing to do with escaping the values to make sure no SQL is in the string that could execute
Related
i have created the next db file -
String sql = ""
+ "CREATE TABLE "+ Constants.TABLE_NAME + " ("
+ Constants.NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Constants.NAME_PERSON + " TEXT"
+ ")";
db.execSQL(sql);
Now what I would like to know is, how to be able to run on the db and to know if a name already exist sin the db, and if so i would like to get the id of that row.
all i can understand is that i should use the
Cursor c= db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
but I don't have a clue what I should do next -
so thanks for any kind of help
you can add this in your DB and call the function passing "to be searched key" as an argument
public boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_INFO, new String[] { KEY_TITLE}, KEY_TITLE + "=?",
new String[] { name }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
if (cursor.moveToFirst()) {
return true;
}else{
return false;
}
}
Where KEY_TITLE is the column name in your table.
Take more example on this:
AndroidSQLite
AndroidSQLite with multi tables
Make a SELECT request. Then check with if(cursor.moveToFirst()) if your name is already existing. (moveToFirst() return true if there is at least 1 value).
So if your value is existing, juste get its id with cursor.getString(cursor.getColumnIndex("_id"));
to update a row in data base when i press a button
public void updateContact(long id, String x, String y,String angle)
{
ContentValues editCon = new ContentValues();
editCon.put(KEY_X, x);
editCon.put(KEY_Y, y);
editCon.put(KEY_ANGLE, angle);
ourDatabase.update(DATABASE_TABLE, editCon, KEY_ROWID + id, null);
}
and i use it entry.updateContact(1, Double.toString(db1), Double.toString(db2), Double.toString(db3));
but i get the exception: no such colum: _id1 (code1): , while compiling: UPDATE SavedTable SET position_y=?, position_x=?, position_angle=? WHERE_id1
even though i have a database with one row ( i create the entry in my oncreate method of main activity)
KEY_ROWID + id will not work as you expect! KEY_ROWID is probably a String containing _id and your id variable contains 1 which will result in _id1.
You need this:
ourDatabase.update(DATABASE_TABLE, editCon, KEY_ROWID + "=" + id, null);
or better:
ourDatabase.update(DATABASE_TABLE, editCon, KEY_ROWID + "=?", new String[]{String.valueOf(id)});
EDIT:
// pseudocode
Cursor c = ourDatabase.query(DATABASE_TABLE, null, null....);
if (c != null) {
if (c.getCount() >= 1) {
// there is an entry - just update
} else {
// no entry - create entry
}
} else {
// error? But definitively no entry so create one
}
You need to fix your update() method:
db.update(DATABASE_TABLE, editCon, KEY_ROWID + " = ?",
new String[] {String.valueOf(id)});
Problem was that you specified incorrect WHERE clause. You wrote this:
KEY_ROWID + id
this is translated on the database layer as _id1 where it was interpreted as column.
You needed _id = 1 and this is achieved by KEY_ROWID + " = ?" where placeholder will be replaced with value from string array.
I'm creating a database for my game, everything is working until I want to query one item.
I have been trying few different methods and I can't make it work. I just simply don't see the error in my code.
The code is as follows:
public Item getItem(String icon) {
String[] columns = {KEY_ID, KEY_TYPE, KEY_ICON, KEY_LEVEL, KEY_ARMOR, KEY_DAMAGE, KEY_BUY, KEY_SELL};
Cursor cursor = db.query(DB_TABLE, columns, KEY_ICON + "=" + icon,
null, null, null, null);
Item item=null;
if(cursor != null && cursor.moveToFirst()) {
item= new Item(cursor.getString(TYPE_COLUMN),
cursor.getString(ICON_COLUMN),
cursor.getString(LEVEL_COLUMN),
cursor.getString(ARMOR_COLUMN),
cursor.getString(DAMAGE_COLUMN),
cursor.getString(BUY_COLUMN),
cursor.getString(SELL_COLUMN)
);
}
return item;
}
The error I'm getting is
No such column: fast_boots (code 1): while compiling: SELECT id, type,
icon, level, armor, damage, buy, sell from items where icon=fast_boots
When trying to find .getItem("fast_boots"); I do see the fast_boots in my sql database
To make the query work, maybe you should try this :
KEY_ICON + "= '" + icon + "' "
As 'icon' is a string value. Since you're not specifying it, it is probably trying to understand it as being a column in the projection
This is the wrong way of implementing such functionality, though. Do not perform database queries on the getItem() method itself (main thread), it deserves to run in background, so it won't affect the main thread.
Please read about AsyncTask.
Try this
Cursor cursor = db.query(DB_TABLE, columns, KEY_ICON + "='" + icon +"'",
null, null, null, null);
I added '
I was trying to update a row in sqlite db, but it gives syntax error. I think I'm missing something but I can't see it. Maybe you can help me.
Update code:
public void updateEntry(String oldname,String name,String mail, String phone,String adres)
{
ContentValues args = new ContentValues();
args.put(COLUMN_NAME, name);
args.put(COLUMN_EMAIL, mail);
args.put(COLUMN_PHONE, phone);
args.put(COLUMN_ADDRESS, adres);
sqLiteDatabase.update(MYDATABASE_TABLE, args,COLUMN_NAME + "=" + oldname, null);
}
Calling update (By the way t,t2,t3,t4 are EditTexts)
mySQLiteAdapter.updateEntry(isim, t.getText().toString(), t2.getText().toString(), t3.getText().toString(), t4.getText().toString());
Errors
07-30 11:34:56.487: E/AndroidRuntime(1990): android.database.sqlite.SQLiteException: near "smith": syntax error: , while compiling: UPDATE MY_TABLE SET Name=?, Phone=?, Email=?, Address=? WHERE Name=john smith
First I thought, I didn't give any address or phone as string, but I printed them and I see the correct values. Any idea where my fault is?
It is because you have not escaped oldname string which contains john smith.
use sqLiteDatabase.update(MYDATABASE_TABLE, args,COLUMN_NAME + "='" + oldname + "'", null);
or use
String whereClause = COLUMN_NAME + "=?";
String[] whereArgs = new String[] {oldname};
sqLiteDatabase.update(MYDATABASE_TABLE, args, whereClause, whereArgs, null);
I would like to update my SQL lite database with the native update-method of the SQLiteDatabase class of android.
ContentValues dataToInsert = new ContentValues();
dataToInsert.put("name", "flo");
dataToInsert.put("location", "flotown");
String where = "id" + "=" + id;
try{
db.update(DATABASE_TABLE, dataToInsert, where, null);
}
catch (Exception e){
String error = e.getMessage().toString();
}
but I get following error:
android.database.sqlite.SQLiteException: near "15": syntax error: ,
while compiling: UPDATE mytable SET location=?, name=? WHERE
id=2010-09-21 15:05:36.995
I don´t know what should be the problem. Somehow the values do not arrive in the SQL statement. I did nearly the same with the insert method and that worked quite fine.
You're using the update function wrong. It should be like this:
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(id)};
db.update(DATABASE_TABLE, dataToInsert, where, whereArgs);
The Strings in the whereArgs array gets substituted in for each '?' in the where variable.
ie. if you had where = "name=? AND type=? then the first '?' would get replaced by whereArgs[0] and the second by whereArgs[1].
Actually, you just need to add apostrophes to your where clause. So it ought to be:
String where = "id='" + id + "'"
(note: however, this is not best practice, as it theoretically leaves open to injection attacks)
I have an other approach
public boolean updateEmployee(TalebeDataUser fav) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.COLUMN_ID, fav.getId());
contentValues.put(DBHelper.COLUM_AD, fav.getAd());
contentValues.put(DBHelper.COLUMN_NUMARA, fav.getNumara());
contentValues.put(DBHelper.COLUMN_YURD_ID, fav.getYurtID());
contentValues.put(DBHelper.COLUMN_EGITIM_ID, fav.getEgitimTur());
contentValues.put(DBHelper.COLUMN_TEL, fav.getTel());
contentValues.put(DBHelper.COLUMN_EMAIL, fav.getEmail());
contentValues.put(DBHelper.COLUMN_ADDRESS, fav.getAdres());
String whereClause = DBHelper.COLUM_AD + " = ? AND " + DBHelper.COLUMN_NUMARA + " = ? ";
final String whereArgs[] = {fav.getAd(), String.valueOf(fav.getNumara())};// old nameler taranıyor
int affectedRows = database.update(DBHelper.TABLE_NAME_OGR, contentValues, whereClause, whereArgs);
return affectedRows > 0;
}
Actually what exactly you written is correct. The syntax is correct.
But you have to check these.
String where = "id" + "=" + id;
In the above declaration "id" should be type number and id should be int.
And if id is a type of TEXT then follow #Adam javin answer.