Issue with rawQuery() in android - android

I am trying to execute a query to retrieve some data from the table.
Below is my query:
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber="+"'myCustomNumber'", null);
where myNumber is type of 'TEXT'
But every time I am getting cursor.getCount() = 0;
It seems there's a mistake in my query.
Please let me know the correct way of writing above query.

In your query the parameter passed as myNumber has become a text due the double quotes around it.
Change it to,
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber = ' " + myCustomNumber + "'", null);

I think you should be use below code :
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber='"+myCustomNumber+"'", null);
i hope it will work for you.

Try this
String phoneNo = "0000000000";
String query = "Select * from where mynumber = '" +phoneNo+ "'";
cursor = myDB.rawQuery(query,null);

you can execute that query i.e.
rawQuery("SELECT * FROM myTable WHERE myNumber= = ? ", new String[] {"myCustomNumber"});

In the query that you have used, the number has not been passed in quotes.
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber="+"'myCustomNumber'", null);
That query would mean myNumber= myCustomNumber literally, and not a variable value.
You need to add the quotes before and after your myCustomNumber like:
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber="+"'"+myCustomNumber+"'", null);

Related

Android SQLITE does not execute queries with arguments

I fail queries with arguments, What am I doing wrong?
I need the following query:
cursor = bd.rawQuery("SELECT * FROM user WHERE user.name=?", new String[]{"%"+nombre+"%"});
I tried the following and they also fail:
cursor = bd.rawQuery("SELECT * FROM user WHERE name=?", new String[]{"%"+nombre+"%"});
cursor = bd.rawQuery("SELECT * FROM user WHERE user.name=?", new String[]{nombre});
This works:
cursor = bd.rawQuery("SELECT * FROM user ", null);
Thanks for your help
As Mike said in your comments
cursor = bd.rawQuery("SELECT * FROM user WHERE name LIKE ? ", new String[]{"%" + nombre + "%"});
or if you really wanna use like this:
cursor = bd.rawQuery("SELECT * FROM user ", null); where second parameter is null.
use escaped string instead:
cursor = bd.rawQuery("SELECT * FROM user WHERE name LIKE '%" + nombre.replaceAll("'","''") + "%' ", null );
or use GLOB like here described.
Please try this, List out users with name foo.
cursor = bd.rawQuery("SELECT * FROM user WHERE name = ?", new String[] {"foo"});
OR
cursor = bd.rawQuery("SELECT * FROM user WHERE name LIKE ?", new String[] {"foo"});
SQLiteDatabase rawQuery document reference
try this
cursor = bd.rawQuery("SELECT * FROM user WHERE name= '%"+ nombre + "%'", null);

android where clause query not working

String name="xyz";
String sql="select * from "+table_name+" where person_name='"+name+"'";
Above query is working fine. but if I replace person_name with any other column name like person_item or person_trip, no results are shown and there is no error.
String sql="select * from "+table_name+" where person_item='"+name+"'";
This query doesn't work.
What can be the possible error? I have been trying to get this work for last 7 days. Please help, thanks in advance.
You could try this - using a cursor
Where myDB is an instance of SQLiteDatabase...
Cursor c = myDB.rawQuery("SELECT * FROM " + table_name , null);
int ITEM_COLUMN = c.getColumnIndex("person_item");
myDB.execSQL("SELECT * FROM "+table_name+" WHERE "+c.getColumnName(ITEM_COLUMN)+" = "+name+";");
You could read more about cursors and their interaction with databases here:
http://developer.android.com/reference/android/database/sqlite/SQLiteCursor.html

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' ";

SQL using with clause not working

My question is why this query does not work?
Cursor c = db.rawQuery("SELECT * FROM tbl_staff WHERE PMajor = '%" + spin.getSelectedItem().toString() + "%'", null);
Cursor c: it is a cursor for handling my query
tbl_staff: my table that consist of PName, PMajor, PCert
spin: is spinner that has values which I need for my database query.
When I use:
if (c.moveToNext())
else (log.d("error query","couldn't do the query!");)
It goes to else statement and moveToNext() doesn't work.
Instead of using =, which checks for equality, use keyword LIKE, which matches a pattern.
Cursor c = db.rawQuery("SELECT * FROM tbl_staff WHERE PMajor LIKE '%" + spin.getSelectedItem().toString() + "%'", null);

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