Sqlite Select Query with rawQuery at Android - android

I know it is a basic question, but i can not find problem.
I try to get some columns with rawQuery.
SQLiteDatabase db=database.getReadableDatabase();
try
{
String sql="SELECT * FROM CAR WHERE name = ";
Cursor crs = db.rawQuery(sql+"5P", null);
}
I always get the same exception.
android.database.sqlite.SQLiteException: **unrecognized token**: "5P": , while compiling: SELECT * FROM CAR WHERE name = 5P
I have 5P at CAR table, i am sure because i used it other queries.

You either need to quote that value, or better yet, use positional parameters:
String[] args={"5P"};
Cursor crs=db.rawQuery("SELECT * FROM CAR WHERE name = ?", args);
The advantage of using positional parameters is that SQLite will handle quoting the string, escaping any embedded quotes, etc.

Related

How to use wildcards in a SQLite query?

I am trying to fetch data which contains specific string but query is not working, following is method for fetching data.
public Cursor getSearch(String item) {
SQLiteDatabase db = this.getReadableDatabase();
String mQuery = "SELECT * FROM hadiths WHERE text LIKE %"+item.toString()+"%";
Cursor cursor = db.rawQuery(mQuery, null);
return cursor;
}
Logcat shows following error.
Caused by: android.database.sqlite.SQLiteException: near "%": syntax error (code 1): , while compiling: SELECT * FROM hadiths WHERE text LIKE %fast%
I know that the wildcard %% and string variable item is causing issue but how do I use string variable along with wildcard?
Edit:
As mentioned below by Jiří, parameters should be used to help prevent SQL injection issues.
In order to add parameters you could do something similar to this:
String mQuery = "SELECT * FROM hadiths WHERE text LIKE ?”;
String param1 = “%” + item + ”%”;
Cursor cursor = db.rawQuery(mQuery, new String [] {param1});
In order to add another parameter:
String mQuery = "SELECT * FROM hadiths WHERE text LIKE ? AND Name = ?”;
String param1 = “%” + item + ”%”;
String param2 = name;
Cursor cursor = db.rawQuery(mQuery, new String [] {param1, param2});
This code is a bit cumbersome, but it is to illustrate that the parameters must be added in the order in which they are should be added to the query.
see SQLite documentation:
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase
Original answer here for posterity. WARNING Dangerous SQL injection issue!
You need to add single quotes to the query.
String mQuery = "SELECT * FROM hadiths WHERE text LIKE '%"+item+"%'";
Take a look at the SQLite docs:
https://www.tutorialspoint.com/sqlite/sqlite_like_clause.htm
Note: There is no need to use toString() since "item" is already of type String.

Android Sql. Query single coloumn, multiple values

I have database with three columns.
I would like to query the database, based on one column which can have multiple values.
For single parameter we can the normal query method where cardName is String[]
Cursor cursor = database.query(Database.TABLE_COUPON_CARD, allColumns,Database.COLUMN_CARD_NAME + " = ?", cardName, null, null,null);
but if there are more than one value, I get a Android SQLite cannot bind argument exception
For multiple values of the same column we can use IN statement but, here how do I write the QUERY or how should i form the rawQuery
String whereClause = Database.COLUMN_CARD_NAME+ " IN(?)";
Cursor cursor = database.query(Database.TABLE_COUPON_CARD, allColumns,whereClause,new String[][]{cardName}, null, null,null);
Android QUERY doesnot take array of array.
What should the correct query be?
TEMPORARY SOLUTION
Currently I have created a method which dynamically creates the clause.
private static StringBuilder buildInClause(String[] myStringArray){
StringBuilder fullString=new StringBuilder();
fullString.append("(");
for(int i=0;i<myStringArray.length;i++){
fullString.append(" '"+myStringArray[i]+"' ");
if(i!=myStringArray.length-1){
fullString.append(",");
}
}
fullString.append(")");
return fullString;
}
If anyone has any other solution please do share.
For two values: IN(?,?). For three values: IN(?,?,?). Get the idea? Each ? corresponds to a single literal in the selection args array.

Android: Getting row by id

I'm trying to get database row by it's ID, but somehow query doesn't return that row. The sql query SELECT * From Table1 Where _id = 100 works good, so I don't know what's the reason. Here is the code of the query:
String [] selectedArgs = new String [] {String.valueOf(selectedItemId)};
String selection = Tables.Table1.COLUMN_ID + "=?";
String [] columns = {Tables.Table1.COLUMN_ID, Tables.Table1.COLUMN_NAME};
Cursor c = foodDB.query(Tables.Food.TABLE_NAME, columns, selection, selectedArgs, null, null, null);
Does anybody have any suggestions?
The problem is that your ID field is a number, while the parameter is a string; the query function does not allow other parameter types for some strange reason.
Try using an expression like COLUMN_ID + " = CAST(? AS INTEGER)".
If your query had only one result column, you could use a separate SQLiteStatement object where you'd be able to use bindLong().
Just in case somebody need it, i have used rawQuery() method for such type of query to work, because query() doesn't work.

What is the correct syntax for SELECT statement and WHERE clause?

I am trying to explore android and I just started using SQLite database. I'm wondering on what is the right syntax for selecting a single row from a table, where the row I want to select is from the value entered from a user using editText. Thanks in advance.
I'm going to disagree with both of the answers above. What if the user enters this query:
Bobby Tables'; drop table yourTable;
See: http://xkcd.com/327/
I believe you should do this instead:
String query = "select * from TABLE_NAME WHERE column_name=?";
String[] selection = new String[1];
selection[0] = users_entered_value;
Cursor c = db.rawQuery(query, selection);
ETA: Actually, the more I think about it, the more I think you're going in the wrong direction. If your app depends on a database query returning exactly one unique match to an arbitrary string entered by the user, it's probably going to be broken a great deal of the time.
What you should probably do is something like this:
String query = "select * from TABLE_NAME WHERE column_name LIKE ?";
String[] selection = new String[1];
selection[0] = "%" + users_entered_value + "%";
Cursor c = db.rawQuery(query, selection);
and then iterate through the results and pick a "best" match according to your own criteria.
Also, you should create the table with case-insensitive matching for the column(s) you're going to be searching.
SQLiteDatabase db;
db.rawQuery("select * from yourTable where your_column_name = 'users_entered_value' limit 1", null);
SQLiteDatabase db;
// make connection to your database ;
Cursor c = null ;
String SQL = "select * from TABLE_NAME where column_name='VALUE'";
c = db.rawQuery(SQL);
c contains your result array of query you fired.
You can retrieve values using loop.

android sqLite prob with where clause

I am building a cursor for a select query. The WHERE section lookup value refers to a variable which is a path so it has several full stops in it.
The query doesnt like this and errors , the error says a col doesn't exist named with a name which is the lookup value i.e the path with stops in it. If I use the sqlEscape util on the variable it doesnt cause an error but the lookup fails.
Any suggestions please?
Without a bit of your code it is hard to say but I'm guessing you are putting your where clause together like this:
String value = "some.thing.or.other";
String where = "FIELD = " + value;
Try building a parameterized where clause instead
String value = "some.thing.or.other";
String where = "FIELD = ?";
SQLiteDatabase db = fDbOpener.getReadableDatabase();
Cursor results = db.query(TABLE_NAME, COLUMNS_LIST, where, new String[] { value }, null, null, null);
When you run the query method now, SQLite will substitute your value into the where clause specifically as a value - it won't try to interpret the value in any way so it can't mistake the full stops for syntax.

Categories

Resources