Problem using variable in a Query - android

I am banging my head over this for several hours, I tested many ways and I know where the proble is, but I just can't figure out how to fix it, I need an external point of view here.
That's my query code:
public Cursor getAllExpensesUser(int user){
String sql = "SELECT * FROM expense WHERE _id IN (SELECT id_expense FROM forwho WHERE id_user = "+ user +")";
return mDb.rawQuery(sql, null);
}
With this query it returns nothing.
When using the following query it returns my desired rows... obviously im using the id number directly.
`String sql = "SELECT * FROM expense WHERE _id IN (SELECT id_expense FROM forwho WHERE id_user = 2)";`
I have tried also with arguments:
public Cursor getAllExpensesUser(int user){
String sql = "SELECT * FROM expense WHERE _id IN (SELECT id_expense FROM forwho WHERE id_user = ?)";
String[] arguments = {Integer.toString(user)};
return mDb.rawQuery(sql, arguments);
So bacically the problem is when I am using a variable.
Can anyone see where I am messing it up?
Thank you

It should be WHERE id_user = '" + user + "')";
SQL requires single quotes around data on the right of the equals.

try to replace
String sql = "SELECT * FROM expense WHERE _id IN (SELECT id_expense FROM forwho WHERE id_user = "+ user +")";
with
String sql = new String("SELECT * FROM expense WHERE _id IN (SELECT id_expense FROM forwho WHERE id_user = "+ String.valueOf(user) +")");
EDIT: use String.valueOf instead of Integer.toString

Related

SQLite: Select using LIKE '%?%' with rawQuery

I am trying to use a select statement to query some data from the database's table .
when i type =? the query succeed , but when i use LIKE %?% instead i got this error in logcat:
FATAL EXCEPTION: main
Process: com.example.ahmed.bus_time_djerba4, PID: 4178
java.lang.IllegalArgumentException: Cannot bind argument at index 2 because the index is out of range. The statement has 0 parameters.
and this is my methode that call the database:
public String QuerySQL(String DepartStation,String Destination){
String result="";
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.rawQuery("select distinct * from "+TABLE_Name+" where "+Col_3+" LIKE '%?%' and "+Col_4+" LIKE '%?%'", new String[]{DepartStation,Destination});
if(c.getCount()==0) {result="Data not found";c.close();}
else {
while (c.moveToNext()) {
//affichage des lignes
int ligne = c.getInt(1);
String Station = c.getString(2);
String Dest = c.getString(3);
String hours = c.getString(4);
result += "\n" + ligne + "|" + Station + "-" + Dest + " " + hours;
}
c.close();
}
return result;
}
what is the problem ? please
The Problem is with the SQL query you have used.
you are giving ? A String which is not acceptable for prepare statements.
select distinct * from table_name where X like '%?%'; is not correct because ? will be a string with double quotation inside a quotation like '%"your_string"%'.
instead write:
select distinct * from table_name where X like ?;
and for ? use "'%your_string%'". you can apply this to your array of string too.
You should use:
Cursor c=db.rawQuery("select distinct * from "+TABLE_Name+" where "+Col_3+" LIKE \"%"+DepartStation+"%\" and "+Col_4+" LIKE \"%"+Destination+"%\"", new String[]{};
instead of this:
Cursor c=db.rawQuery("select distinct * from "+TABLE_Name+" where "+Col_3+" LIKE '%?%' and "+Col_4+" LIKE '%?%'", new String[]{DepartStation,Destination});

SQLite Querying with user defined data

I have a query that joins 2 tables get the required data on my android, what picture here is the user clicks on an item and the item's ID is used to query the right data in the Database, I know I can simply use database.query() but it according to my research it is used for simply database querying only, in my case I should use rawQuery() which provides more power of the database. below is my query which links table 1 to table 2 to get the users name from table one and user last name from table 2 if the foreign key is the same as user key
Assume this is my query:
String sQuery = SELECT table1.ID, table2.userlastname FROM table1, table2 WHERE "+table1.ID = table2.foreign;
If i try to specify the user id like below it gets all data in the database table which means i should replace id with "=?" but how do I do this when I am dealing which such a query, one that uses db.rawQuery() instead of db.query()
`private Object userInfo(int id)
{
String sQuery = SELECT table1.ID, table2.userlastname
FROM table1, table2 WHERE "+table1.ID = id;
}`
Basically you replace the parameter by question marks '?' and pass them through a String array in the order they appear in the query.
String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign;
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);
it did not work until I joined table 2 like:
`String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);`

how to update sqlite using expression?

I would like to do this query in SQLite:
update table1 set col1 = (? || substr (col1, col2))
where table1.id in (select id from table2 where condition);
I'm not sure how to do this. SQLiteDatabase.rawQuery doesn't work. All the other APIs I've seen don't allow the expression in the "set" part. If I could use SQLiteStatement, it would work. But that constructor is only visible in its package, not to my code :(
Ideally, I would do something like this:
String query =
"update Table1 set " +
" col1 = (? || substr (col1, col2)), " +
" col2 = ? " +
"where Table1.id in " +
" (select id from Table2 where col3 = ?)";
String[] args = new String[3];
args[0] = arg0;
args[1] = arg1;
args[2] = arg2;
SQLiteStatement statement = new SQLiteStatement (getDb(), query, args);
int rowsUpdated = 0;
try
{
rowsUpdated = statement.executeUpdateDelete();
} finally {
statement.close();
}
Any ideas? Thanks.
Usually when we want to run CRUD operations we use SQLiteDatabase.execSQL().
SQLiteDatabase.rawQuery() is generally used for select queries and it returns a Cursor with the result set.
Although rawQuery() should theoretically work because according to the docs
Runs the provided SQL and returns a Cursor over the result set.
But others have reported that it doesn't work with update queries, so I'm not entirely sure about that.

Issue in Inner Join Query in Android | Trouble in Sqlite query

I am in trouble I have 2 table in sqlite and want both field from them but I did not got any thing. I have tried a lot on stack overflow but no one is work for me..
My query is something like that-
public List<HeadItemGroup> getAllExpense() {
List<HeadItemGroup> expenseList = new ArrayList<HeadItemGroup>();
db = sqlHp.getReadableDatabase();
String selectquery = "SELECT table_expense.item_id AS ID,table_item.item_id AS ID2,* FROM table_expense INNER JOIN table_item ON table_expense.item_id=table_item.item_id";
System.out.println("selectquery value..."+selectquery);
cursor = db.rawQuery(selectquery, null);
while (cursor.moveToNext()) {
HeadItemGroup record = new HeadItemGroup();
record.setExpId(cursor.getInt(cursor.getColumnIndex(EXPENCE_ID)));
record.setItemId(cursor.getInt(cursor.getColumnIndex(ITEM_ID)));
record.setHeadId(cursor.getInt(cursor.getColumnIndex(HEAD_ID)));
record.setDate(cursor.getString(cursor.getColumnIndex(EXPENCE_DATE)));
record.setPrice(cursor.getString(cursor.getColumnIndex(EXPENCE_PRICE)));
record.setLocationLat(cursor.getString(cursor.getColumnIndex(LOCATION_LAT)));
record.setLocationLon(cursor.getString(cursor.getColumnIndex(LOCATION_LON)));
record.setLocationName(cursor.getString(cursor.getColumnIndex(LOCATION_NAME)));
record.setCurrency(cursor.getString(cursor.getColumnIndex(CURRENCY_SYMBOL)));
record.setDescription(cursor.getString(cursor.getColumnIndex(DESCRIPTION)));
record.setItemName(cursor.getString(cursor.getColumnIndex(ITEM_NAME)));
record.setGroupId(cursor.getInt(cursor.getColumnIndex(GROUP_ID)));
expenseList.add(record);
System.out.println("total value value**************"+ cursor.getString(cursor.getColumnIndex(EXPENCE_PRICE)));
System.out.println("total value value**************"+ cursor.getString(cursor.getColumnIndex(ITEM_NAME)));
System.out.println("total value value**************"+ cursor.getString(cursor.getColumnIndex(GROUP_ID)));
}
return expenseList;
}
And when I am trying with same table for left outer join it's work..
String selectquery="select exp_id as _id, * from table_expense d left outer join table_item u on ( d.item_id=u.item_id)";
But i need all data from both table. Please help me...

Android Sqlite no result

what do you think my problem is.
I am querying a sqlite database.
This code doesn't give any result.
String sql = " select _id from MYTABLE where _id = ? ";
Cursor cur = mDb.rawQuery(sql, new String[] {"5653"}) ;
but if I am executing the query without parameters like this:
String sql = " select _id from MYTABLE where _id = 5653 ";
Cursor cur = mDb.rawQuery(sql, null) ;
One row is returned as expected.
Many thanks.
That happens because the values are bound as strings, and that column is (i am guessing) an int. so the where clause will end up being
where _id = "5653"
From rawQuery javadoc for selectionArgs -
You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
Try this:
String sql = " select _id from MYTABLE where _id = '5653' ";

Categories

Resources