Hi to All I am new to Android.
I am using SQLite DataBase in my Application
meanwhile I am Written Queries using +
Like delete from tablename where value = + value;
this is my query
String delete_query = "delete from " + tableName
+ " where title = '" + title + "'";
database.execSQL(delete_query);
I want to write this Query using placeholder ?.
so that i tried
database.delete(tableName, title + "?" , new String[] {title});
instead "?" i tried (?)/('?')/'?'
but it is giving me an error....
can any one tell me how to write appropriate query using ?.....
Thanks in Advance.
Mahaveer
Make sure you have put the equal sign:-
database.delete(tableName, title + "=?" , new String[] {title});
As far as possible, try to use the less raw queries you can. Two advantages:
Query parameters will be escaped by the system (protection against SQL injection)
The code will be more readable
See the delete function of SQLiteDatabase class
public int delete (String table, String whereClause, String[]
whereArgs)
Convenience method for deleting rows in the
database.
table the table to delete from
whereClause the optional WHERE clause
to apply when deleting. Passing null will delete all rows.
Returns the number of rows affected if a whereClause is passed in, 0
otherwise. To remove all rows and get a count pass "1" as the
whereClause.
In your case:
final String where = "title=?";
final String[] args = new String[] { title };
database.delete(tableName, where, args);
Related
I am trying to delete a row from my table if 2 columns equal to what the user entered.
E.g. I have 2 textfields in which the user entered something in both e.g. "chicken" and in the other textfield "car". I want to delete the row in which those 2 values are in a row. I think it will be something like: delete from ~tablename~ where food = chicken AND vehicle = car.
Im not sure how to write that in sqlite in android.
I have my SQLitedatabase object and have called the delete method on it, but not sure what to put in the parameters
EDIT = I've managed to do it. Thanks for the below answers but this is how I've done it:
sqlitedb.delete("Random", "food =? AND vehicle=? ", new String[]{tv.getText.toString(),tv1.getText.toString()});
tv and tv1 are textfields in my case. Random is my table's name.
The sql query will look like -
String sqlQuery = "DELETE FROM <table_name> WHERE food = '"+ <food_name> + "' AND vehicle = '" + <vehicle_name> + "'";
You want something like:
String table_name=~tablename~;
String table_column_one=food;
String table_column_two=vehicle;
database.delete(table_name,
table_column_one + " = ? AND " + table_column_two + " = ?",
new String[] {"chicken", "car"});
Check SQLiteDatabase's documentation on delete function for more info.
SQLite accepts conditionals in the WHERE clause as regular SQL.
I'm making an Android app and using a SQLite database. In particular I'm using the rawQuery method on a database obtained through a SQLiteOpenHelper. The query I build makes use of the ? marks as placeholders for the real values, which are passed along as an array of objects (e.g., select * from table where id = ?).
The question is, is it possible to get the query with the marks already replaced, at least from the cursor returned from the rawQuery method? I mean something like select * from table where id = 56. This would be useful for debugging purposes.
It's not possible. The ? values are not bound at the SQL level but deeper, and there's no "result" SQL after binding the values.
Variable binding is a part of the sqlite3 C API, and the Android SQLite APIs just provide a thin wrapper on top. http://sqlite.org/c3ref/bind_blob.html
For debugging purposes you can log your SQL with the ?, and log the values of your bind arguments.
You could form it as a string like this
int id = 56;
String query = "select * from table where id = '" + id + "'";
and then use it as a rawQuery like this (if I understood your question properly)
Cursor mCursor = mDb.rawQuery(query, null);
You can also use the SQLiteQueryBuilder. Here is an example with a join query:
//Create new querybuilder
SQLiteQueryBuilder _QB = new SQLiteQueryBuilder();
//Specify books table and add join to categories table (use full_id for joining categories table)
_QB.setTables(BookColumns.TABLENAME +
" LEFT OUTER JOIN " + CategoryColumns.TABLENAME + " ON " +
BookColumns.CATEGORY + " = " + CategoryColumns.FULL_ID);
//Order by records by title
_OrderBy = BookColumns.BOOK_TITLE + " ASC";
//Open database connection
SQLiteDatabase _DB = fDatabaseHelper.getReadableDatabase();
//Get cursor
Cursor _Result = _QB.query(_DB, null, null, null, null, null, _OrderBy);
How can I delete multiple rows by a list of IDs in Android SQLite database?
I have defined a general delete method in this manner:
protected void deleteWhere(String whereClause, String[] whereArgs) {
try {
databaseHelper.getWritableDatabase().delete(
getTableName(), whereClause, whereArgs);
} finally {
databaseHelper.close();
}
}
And now I'm trying to call it with a list of IDs:
public void deleteAll(Iterable<T> entities) {
Iterable<Long> ids = Iterables.transform(entities, getId);
String whereClause = getIdColumn() + " IN (?)";
String[] whereArgs = { TextUtils.join(",", ids) };
deleteWhere(whereClause, whereArgs);
}
If the ID list contains for example the values [1, 2, 42], then I assume the resulting SQL should be:
DELETE FROM tableName WHERE _id IN (1,2,42);
But this doesn't seem to work correctly. If the list contains only 1 ID, then it is correctly deleted. However, if I provide multiple values, than zero rows are affected. What am I doing wrong?
When you give a single string as whereArgs, a single string ends up in the SQL command, as if you had written this:
... WHERE _id IN ('1,2,42')
This would compare each _id value against the value '1,2,42', which of course does not work.
If you use three parameter markers and give three strings in the whereArgs array, you would end up with three strings, like this:
... WHERE _id in ('1','2','42')
This works only when the _id column has integer affinity, which is true for a column declared as INTEGER PRIMARY KEY, but not in the general case.
The Android database API does not allow query parameters to have any type but string.
When using integers, you should just insert them directly (as in ianhanniballake's answer):
String whereClause = getIdColumn() + " IN (" + TextUtils.join(",", ids) + ")";
You can't use whereArgs for IN statements due to the escaping done by whereArgs (unless you make a separate ? for each value) - instead, you have to embed the ids in your where statement:
String whereClause = getIdColumn() + " IN (" + TextUtils.join(",", ids) + ")";
deleteWhere(whereClause, null);
Each "?" will only bind to a single value. So if your id list has three values, your whereClause would need to be "_id IN (?,?,?)"
I get a string stored in the db to change it. I'm stuck in the method db.update because I have to change all the strings that match the value received. for example I have 15 records in field1 with the string "sun" and change it to "sun1" need to be changed all the correspondents.
I tried that but it does not work
cv.put(MyTable.FIELD1, Ec.getText().toString());
String cat_modificare = (i.getStringExtra("value"));
db.update(MyTable.TABLE_NAME, cv, cat_modificare + "=" + MyTable.FIELD1, null);
When you write something into the whereClause, it is interpreted as a column name unless you format it correctly.
String values should always be used as parameters:
db.update(MyTable.TABLE_NAME, cv,
MyTable.FIELD1 + " = ?",
new String[] { cat_modificare });
So I have data in my database & the value of category is set to "Breakfast"
When I execute the below Query with whereClause as
1:final String whereClause = RECIPE_ID + "=1";
It returns me the data for that RECIPE_ID
But when I execute the query with whereClause as
2:final String whereClause = RECIPE_CATEGORY + "='" + category.trim() + "'";
It doesn't return anything... So I guess my code is working fine as it returns result
RECIPE_ID but I donno why it doesn't return data for the 2nd whereClause
Hope this makes sense..
final String whereClause = RECIPE_CATEGORY + "='" + category.trim() + "'";
// ask the database object to create the cursor.
cursor = db.query(
RECIPE_TABLE,
new String[]{
RECIPE_ID,
RECIPE_CATEGORY,
RECIPE_THIS_TITLE,
RECIPE_THIS_SUBTITLE,
RECIPE_THIS_DESCRIPTION,
RECIPE_THIS_IMAGE,
RECIPE_THIS_CALORIES,
RECIPE_THIS_FAT,
RECIPE_THIS_SATURATED,
RECIPE_THIS_TRANS,
RECIPE_THIS_CARBS,
RECIPE_THIS_SODIUM,
RECIPE_THIS_SUGARS,
RECIPE_THIS_SERVINGS,
RECIPE_THIS_COSTPERSERVING,
RECIPE_THIS_INSTRUCTIONS,
RECIPE_THAT_TITLE,
RECIPE_THAT_CALORIES,
RECIPE_THAT_FAT,
RECIPE_THAT_SATURATED,
RECIPE_THAT_TRANS,
RECIPE_THAT_CARBS,
RECIPE_THAT_SODIUM,
RECIPE_THAT_SUGARS,
RECIPE_THAT_PRICE
},
whereClause, null, null, null, null
);
The above code will not return any results. Is anything wrong with it?
You really need to form a question here. Posting code does you no good. If your question is as you title implies, then yes you can do a search clause as a string. Just leave out the where. eg dataId = 5 where 'where' is implied.
Edit: to address the question at the bottom that I missed, multiple things could be wrong. One may be that you dont have any data in the database. Or the where clause is executed and none of your data fits the criteria. Check your database. We can't help with that.