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

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});

Related

SQLite query compare content Values

How can I compare column content values? So if content values contain "ted" return all data in cursor.
public Cursor listNotes() {
String username = session.getUser();
String query = "SELECT * FROM Task WHERE " +help.Column_owner+ " = " +username ;
Cursor c = db.rawQuery(query, null);
return c;
}
Here is the error, I am trying to compare username to the content values in the column_create but its not working
no such column: ted (code 1): , while compiling: SELECT * FROM Notes WHERE column_owner = ted
username must be enclosed in apostrophes ('), because it is a string!
Correct your code like this:
String query = "SELECT * FROM Task WHERE " + help.Column_owner + " = '" +username + "'";
Or, better, use a bound parameter (in this case, Android takes care of the apostrophes for you and you're less prone to SQL injection - and, last but not least, you use less string concatenations):
String query = "SELECT * FROM Task WHERE " + help.Column_owner + " = ?";
Cursor c = db.rawQuery(query, new String[]{username});

Get all unique values from SQLite column as string array

I try to get all unique values from database coulmn using SELECT DISTINCT sql command.
But i get exception when my activity is loading, i have this error code in logcat:
05-05 09:08:32.637: E/AndroidRuntime(1314): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: android.database.sqlite.SQLiteException: near "SELECT": syntax error (code 1): , while compiling: SELECT * FROM exerciseTable WHERE SELECT DISTINCTexercise_typefromexerciseTable
I think that i have not wrote the command correctly, here is my code:
public String[] getAllExercies() {
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
Cursor c = ourDatabase.query(TABLE_NAME, null, selecet, null, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
String[] list = new String[c.getCount()-1];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
list[j] = c.getString(dayExercise);
j++;
}
return list;
}
I think you should first checkout these answers here and here in order to see the working of .query() function.
Please note that while using ourDatabase.query() function, the parameters are as follows:
String Table Name: The name of the table to run the query against
String [ ] columns: The projection of the query, i.e., the columns to retrieve
String WHERE clause: where clause, if none then pass null
String [ ] selection args: The parameters of the WHERE clause
String Group by: A string specifying group by clause
String Having: A string specifying HAVING clause
String Order By by: A string Order By by clause
So your third variable should be a WHERE clause, something like:
String[] args = { "first string" };
Cursor c = ourDatabase.query("TABLE_NAME", null, "exercise_type=?", args, null, null, null);
Since you don't need a WHERE clause, for your purposes you might want to use rawQuery() method instead.
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
ourDatabase.rawQuery(selecet, null);
Update
Try the answer from here. Do something like this:
Cursor c = ourDatabase.query(true, "exerciseTable", new String[] {"exercise_type"}, null, null, "exercise_type", null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
//... continue with your further code
Hope this helps else please comment.
Issue:
you have not maintained the space between the words.
Explaination:
suppose, String COLUMN_EXERCISE = "exercise";
and String TABLE_NAME = "tbl_workout";
then
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
simply means,SELECT DISTINCTexercisefromtbl_workout
Solution:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " from " + TABLE_NAME;
Edit:
Kindly use following syntax to fire rawQuery
Cursor c = ourDatabase.rawQuery(selecet,null);
I hope it will be helpful !
You miss all the spaces in your query, you should replace with this:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;

Method to excute query and return results

App won't run - trying to execute query to print certain value
Method:
public Cursor trying(String vg){
String q="SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + vg;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(q,null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Calling method from main
Cursor wow = db.trying("gold");
text = (TextView) findViewById(R.id.textView13);
text.setText((CharSequence) (wow));
At first. Since you are directly adding trying variables into statement, variable must be wrapped to single quotes or it's interpeted as column.
"SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name= '" + vg + "'";
And second "big" problem, look here:
text.setText((CharSequence) (wow));
Here you are trying to cast Cursor to CharSequence but it's not possible. If you want to retrieve data from Cursor you have to use one from the getters methods of Cursor class in your case getString() method:
String quantity = wow.getString(0); // it returns your quantity from Cursor
text.setText(quantity);
Now it should works.
Recommendation:
I suggest you to an usage of parametrized statements which actually use placeholders in your queries. They provide much more safer way for adding and retrieving data to / from database.
Let's rewrite your code:
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name = ?";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(q, new String[] {vg});
It works simply. Placeholder ? will be replaced with your string value.

SQLite rawquery

I am getting an error with a rawquery on Eclipse on a DB in the assets directory. The DB is 'pre-loaded' with tables and data and the SQL string, first comment line, works in SQLite DB browser. When I copy the SQL string to code and modify to remove quotes it errors. The code below is from the 'standard' public class DataBaseHelper extends SQLiteOpenHelper{ .I am new to android/java and would appreciate any assistance or suggestions.
public Cursor getAllSectionDescriptions( String DBtable, String source){
//Works in DB: SELECT "Description" FROM "SectionProps" WHERE Source = "UK"
//String q = "SELECT Description FROM SectionProps WHERE Source = UK " ; <= errors in code
String q = "SELECT Description FROM " + DBtable + " WHERE Source = " + source + " "; //<== errors in code
//06-24 16:53:03.373: ERROR/AndroidRuntime(1000): Caused by: android.database.sqlite.SQLiteException: no such table: SectionProps: , while compiling: SELECT Description FROM SectionProps WHERE Source = UK
Cursor mCursor = myDataBase.rawQuery(q, null);
mCursor.moveToFirst();
return mCursor;
}//end cursor
Looks like you have to put double quotes around your object names. So you'll want to do this:
String q = "SELECT \"Description\" FROM \"" + DBtable + "\" WHERE Source = \"" + source + "\" ";
Note the double quotes preceded by the escape character '\'
To execute queries, there are two methods: Execute db.rawQuery method Execute db.query method To execute a raw query to retrieve all departments:
Cursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id,
"+colDeptName+" from "+deptTable,new String [] {});
return cur;
}
The rawQuery method has two parameters: String query: The select statement String[] selection args: The arguments if a WHERE clause is included in the select statement Notes The result of a query is returned in Cursor object. In a select statement if the primary key column (the id column) of the table has a name other than _id, then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception .

SQLite Query in Android to count rows

I'm trying to create a simple Login form, where I compare the login id and password entered at the login screen with that stored in the database.
I'm using the following query:
final String DATABASE_COMPARE =
"select count(*) from users where uname=" + loginname + "and pwd=" + loginpass + ");" ;
The issue is, I don't know, how can I execute the above query and store the count returned.
Here's how the database table looks like ( I've manged to create the database successfully using the execSQl method)
private static final String
DATABASE_CREATE =
"create table users (_id integer autoincrement, "
+ "name text not null, uname primary key text not null, "
+ "pwd text not null);";//+"phoneno text not null);";
Can someone kindly guide me as to how I can achieve this? If possible please provide a sample snippet to do the above task.
DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).
SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
"uname=? AND pwd=?", new String[] {loginname,loginpass});
#scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:
Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
I also like #Dre's answer, with the parameterized query.
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
See rawQuery(String, String[]) and the documentation for Cursor
Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as
select count(*) from users where uname=boband pwd=password);
Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.
To use selectionArgs you would do something like
final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";
private void someMethod() {
Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
...
}
Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:
String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;
how to get count column
final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;
int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);
This is the most concise and precise alternative. No need to handle cursors and their closing.
If you are using ContentProvider then you can use:
Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
uname=" + loginname + " and pwd=" + loginpass, null, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
If you want to get the count of records then you have to apply the group by on some field or apply the below query.
Like
db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();

Categories

Resources