I am facing a problem in updating a table with multiple columns in where clause of the db.update in sqlite.
Below is what I have tried but not accepting and showing syntax error.
db.getWritableDatabase().update(tablename, update((buy+dupbuy)), (column2+"=? and"+ column3+"=?"),(new String[] {getdate}+" and"+new String[] {stockname}));
In above query
First parameter is tablename to be updated.
second parameter is value to be updated which will point to another class update method where I wrote content values for updating the table
Major one third part is parameters I need to pass in where clause.
but giving syntax error
The method update(String, ContentValues, String, String[]) in the type SQLiteDatabase is not applicable for the arguments (String, ContentValues, String, String)
How can I declare multiple columns in where clause?
Try changing
db.getWritableDatabase().update(tablename, update((buy+dupbuy)), (column2+"=? and"+ column3+"=?"),(new String[] {getdate}+" and"+new String[] {stockname}));
to
db.getWritableDatabase().update(tablename, update((buy+dupbuy)), (column2+"=? and "+ column3+"=?"),(new String[] {getdate,stockname}));
Add a space after the "and" in the WHERE clause and you need to pass a String[] and not String in the whereArgs parameter. Currently you are passing a String
Change the stretch code:
db.getWritableDatabase().update(tablename, update((buy+dupbuy)), (column2+"=? and"+ column3+"=?"),(new String[] {getdate}+" and"+new String[] {stockname}));
To
db.getWritableDatabase().update( tablename, update(buy+dupbuy), column2 + " = ? and " + column3 + " = ?", new String[]{ getdate, stockname } );
Related
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 (?,?,?)"
public static final String KEY_HIGH
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_HIGH + " INTERGE);"
);
}
public long createEntry(String high) {
ContentValues cv = new ContentValues();
cv.put(KEY_HIGH, high);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
String[] columns = new String[]{KEY_HIGH,KEY_NAME};
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null, KEY_HIGH + " DESC");
I am trying to sort by the column KEY_HIGH, however, the result came out like this:
4
3
2
10
11
1
How do I sort them as numbers from highest to lowest?
thanks.
From the Android docs:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Added in API level 1
Query the given table, returning a Cursor over the result set.
Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
Returns
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
See Also
Cursor
Note that the final is named orderBy. This is where you can specify which column (or columns) to sort on. Also note that you do not need to include the "ORDER BY" keywords that you would use in a SQL statement.
I was having the same problem.It has a very simple solution:
In your CREATE_TABLE statement do this: " INTEGER, "+KEY_HIGH+ //your remaining things.
no need for the comma after the last null
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null + " ORDER BY " + KEY_HIGH + " DESC");
I’m trying to query a single table database that I’ve created in my code. To the best of my knowledge the database is being created correctly. The query is supposed to be used to populate a ListView but when I try to use the resulting cursor from my query to create SimpleCursorAdapter, it crashes with: java.lang.IllegalArgumentException: column '_id' does not exist. I am assuming this can be traced to the cursor, and also the cursor seems to be empty.
The database is created in the following way within the onCreate() of my implementation of a SQLiteOpenHelper:
db.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL, title TEXT NOT NULL, path TEXT NOT NULL);");
And then the actual query is set up and executed in my DataHelper Class which is used to interact with the database:
public Cursor selectEntryStartsWith(String partialName , String title)
{
String where = "name LIKE '" + partialName + "%' AND title LIKE '" + title + "'";
if (title== null || title.equals("")){
where = "name LIKE '" + partialName + "%'";
}
Cursor cur = mDatabase.query(TABLE_NAME, new String[] {"_id", "name", "title"}, where, null, null, null, "name");
return cur;
}
The code that uses the cursor is as follows:
Cursor cursor = mDataHelper.selectEntryStartsWith("ex", null); //get all entries that start with "ex"
String [] from = new String [] { "name", "title" };
int [] to = new int [] { R.id.name, R.id.title };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(mContext, R.layout.listview_entry, cursor, from, to);
songList.setAdapter(adapter);
I'm using tabs to this last piece of code is from within the onActivityCreated() of a Fragment; I not that it might be better to extend a ListFragment, but I don't think this is the problem here in particularity.
Sorry in advance if I have missed an information that you may require, I've been banging my head on this problem for some time now.
Do you know the data is actually in the database? Run 'adb shell', cd to your data directory '/data/data/[app package name]/databases'. Then run sqlite3 [db file name]. Run some direct sql queries and make sure data exists.
If there is data there, rather than going right to the SimpleCursorAdapter, run some text queries in code, and see if you can access the results.
Once all of that works out, add the ListView stuff as a last step.
Some things to mention. If the user is typing in query values, you need to escape those statement values. Either use selectionArgs in the query statement:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String)
or use my stripped-down apache commons-lang, and the StringEscapeUtils class.
http://www.touchlab.co/blog/android-mini-commons/
Another thing to consider, although if you're not having trouble, its probably not an issue. 'name' and 'title' might be tricky keywords in sql statements.
The problem was indeed the database was not set up properly, I tried another method of inserting the data i.e. using ContentValues and inserting directly into the database, as opposed to using the precompiled insert statement I was using before.
The insert method now looks like this:
public long insert(String name, String title)
{
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("title", title);
return mDatabase.insert(TABLE_NAME, null, cv);
/* The old code was using this precompiled statement
mInsertStatement.bindString(1, name);
mInsertStatement.bindString(2, title);
return mInsertStatement.executeInsert();
*/
}
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);
I am facing a problem here. I am trying to bulk update my table i.e trying to update multiple rows in the database. The update is simple. I just need to set a column value to 1 which is actually used as a flag in the app. So I want to set the value to 1 and in the where clause I give the string array of all the ids where i want it to set.
But the problem is that it gives me an "android.database.sqlite.SQLiteException: bind or column index out of range:" . However when a single value is provided either as string or an string array, the update works fine.
here is the query
db.update( tableName, cv, Z_ID + "=?", items );
where items is of type String[ ]
kindly tell me what am I missing?
regards
Fahad Ali Shaikh
That is not going to work I believe based on the one line you gave.
If we look at the method call signature :
update(String table, ContentValues values, String whereClause, String[] whereArgs)
so:
ContentValues cv=new ContentValues(); cv.put(colName, new Integer(1));
String[] items = new String []{String.valueOf(Z_ID)}
db.update( tableName, cv, Z_ID + "=?", items );
Does you code look something like this?
Your items array must match up with the where clause. A different example would look something like this:
ContentValues cv=new ContentValues(); cv.put(salesColName, new Integer(4534));
String whereClause = "band=? and album=?"; String whereArgs = new String [] { "U2", "Joshua Tree" };
db.update( tableName, cv, whereClause , whereArgs);