Android SQLite strange issue - android

In my app I have one DB table with that structure:
user TEXT | token text
When I'm doing request to check if this user exist in table, like that:
String whereClause = COLUMN_USER + "==\"" + userName + "\"";
Cursor c = db.query(TABLE_USERS, new String[]{COLUMN_USER, COLUMN_TOKEN}, whereClause, null, null, null, null);
It works for all users. But if variable userName is "user" I got all records back.
Looks like sqllite checks table structure, and return to me all records 'cos name of this column equals to my value that I'm using - user.

I suggest you parameterize the arguments in your where clause:
String whereClause = COLUMN_USER + "=?";
String [] whereArgs = { userName };
Cursor c = db.query(TABLE_USERS, new String[]{COLUMN_USER, COLUMN_TOKEN}, whereClause, whereArgs, null, null, null);

A simple kludge to get rid of this problem would be simply to enclose the query in:
if (userName =! "user") {
//code here
} else {
//open dialog about invalid username
}
Although i'm sure there's a more elegant solution. Input Data sanitizing should be done anyways, and if you're already checking for invalids, maybe just add "user" into the list of rejecteds?

Related

Before inserting a record in the database to validate that there is

Before inserting a record in the database to validate that there is, for example I have a table that has two fields, table fields VA with Customer, First, I want to validate the field if there is no customer registration and if there insert
That i want to do in android using Sqlite
String sql = "SELECT * FROM TABLE WHERE id = '" + id + "'";
Cursor data = database.rawQuery(sql, null);
After this check by following code
if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}
Look at SQLite constraints. This really isn't Android-specific; it's a feature of SQLite.
Try this, it works for me.
String[] args = { myDataToCheck };
c = ourDatabase.query(DATABASE_TABLE, columns,
myColumnToCheck + "=?", args, null, null, null);
if (c.getCount() == 0) {
// doesn't exists
}else{
//exists
}
You have 2 possibilities :
1)make a select to check if there is the same key in database, then insert or update.
2)make directly an update. update will return the number of row updated, if the number is 0, so you can do an insert.

Understanding SQLite Cursor Behavior

I'm writing a method to update default settings in a table. The table is very simple: two columns, the first containing labels to indicate the type of setting, the second to store the value of the setting.
At this point in the execution, the table is empty. I'm just setting up the initial value. So, I expect that this cursor will come back empty. But instead, I'm getting an error (shown below). The setting that I am working with is called "lastPlayer" and is supposed to get stored in the "SETTING_COLUMN" in the "SETTINGS_TABLE". Here's the code:
public static void updateSetting(String setting, String newVal) {
String table = "SETTINGS_TABLE";
String[] resultColumn = new String[] {VALUE_COLUMN};
String where = SETTING_COLUMN + "=" + setting;
System.err.println(where);
SQLiteDatabase db = godSimDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(table, resultColumn, where, null, null, null, null);
System.err.println("cursor returned"); //I never see this ouput
\\more
}
sqlite returned: error code = 1, msg = no such column: lastPlayer
Why is it saying that there is no such column lastPlayer? I thought that I was telling the query to look at the column "SETTING_COLUMN" and return the record where that column has a value "lastPlayer". I'm confused. Can somebody straighten me out? I've been looking a this for an hour and I just don't see what I am doing wrong.
Thanks!
You're not properly building/escaping your query. Since the value lastPlayer is not in quotes, your statement is checking for equality of two columns, which is what that error message is saying.
To properly build your query, it's best to not do this manually with String concatenation. Instead, the parameter selectionArgs of SQLiteDatabase.query() is meant to do this.
The parameters in your query should be defined as ? and then filled in based on the selectionArgs. From the docs:
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.
So, your code would look like this:
String where = SETTING_COLUMN + " = ?";
Cursor cursor = db.query(table, resultColumn, where, new String[] { setting }, null, null, null);

compare sqlite with string

I saved Data in my SQL databank.
Now I want to compare this saved data, with a string
Something like this:
String example = "house";
Now I want to check, if "house" is already in the databank, with a if clause
something like this
if ( example == [SQL Data] ) {
}
else {
}
Now, how can I accomplish this ?
Do something like
String sql = "SELECT * FROM your_table WHERE your_column = '" + example + "'";
Cursor data = database.rawQuery(sql, null);
if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}
stolen from here
Writing my reply to Sharath's comment as an answer, as the code will be messed up in a comment:
Not saying your reply is wrong, but it's really inefficient to select everything from the table and iterate over it outside the database and it shouldn't be suggested as an answer to the question, because it's a bad habbit to do like that in general.
The way I usually do it, if I want to see if some record is present in the database, I do like this. Not gonna argue about using do-while over a normal while-loop, because that's about different preferences ;)
String query = "SELECT * FROM table_name WHERE column_name=" + the_example_string_to_find;
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount() > 0) {
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
// Do whatever you like with the result.
cursor.moveToNext();
}
}
// Getting Specific Record by name.
// in DB handler class make this function call it by sending search criteria.
Records getRecord(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_Auth_Name, KEY_B_PRICE}, KEY_ID + "=?",
new String[]{name}, null, null, null,null);
if (cursor.getCount() > 0)
cursor.moveToFirst();
Records Records = new Records(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return book
return Records;
}
you need to first fetch all the data from the database and next check the data with what you obtained from the database.
Have a look at the link sample database example
suppose you got a cursor object from the database
cursor = db.rawQuery("SELECT yourColumnName FROM "+TABLE_NAME, null);
if(!cursor.moveToFirst()){
}
else{
do {
if(cursor.getString(0).equals(example))
//do something which you want and break
break;
} while (cursor.moveToNext());
}

ANDROID: Can I do SELECT with WHERE clause as String?

So I have data in my database & the value of category is set to "Breakfast"
When I execute the below Query with whereClause as
1:final String whereClause = RECIPE_ID + "=1";
It returns me the data for that RECIPE_ID
But when I execute the query with whereClause as
2:final String whereClause = RECIPE_CATEGORY + "='" + category.trim() + "'";
It doesn't return anything... So I guess my code is working fine as it returns result
RECIPE_ID but I donno why it doesn't return data for the 2nd whereClause
Hope this makes sense..
final String whereClause = RECIPE_CATEGORY + "='" + category.trim() + "'";
// ask the database object to create the cursor.
cursor = db.query(
RECIPE_TABLE,
new String[]{
RECIPE_ID,
RECIPE_CATEGORY,
RECIPE_THIS_TITLE,
RECIPE_THIS_SUBTITLE,
RECIPE_THIS_DESCRIPTION,
RECIPE_THIS_IMAGE,
RECIPE_THIS_CALORIES,
RECIPE_THIS_FAT,
RECIPE_THIS_SATURATED,
RECIPE_THIS_TRANS,
RECIPE_THIS_CARBS,
RECIPE_THIS_SODIUM,
RECIPE_THIS_SUGARS,
RECIPE_THIS_SERVINGS,
RECIPE_THIS_COSTPERSERVING,
RECIPE_THIS_INSTRUCTIONS,
RECIPE_THAT_TITLE,
RECIPE_THAT_CALORIES,
RECIPE_THAT_FAT,
RECIPE_THAT_SATURATED,
RECIPE_THAT_TRANS,
RECIPE_THAT_CARBS,
RECIPE_THAT_SODIUM,
RECIPE_THAT_SUGARS,
RECIPE_THAT_PRICE
},
whereClause, null, null, null, null
);
The above code will not return any results. Is anything wrong with it?
You really need to form a question here. Posting code does you no good. If your question is as you title implies, then yes you can do a search clause as a string. Just leave out the where. eg dataId = 5 where 'where' is implied.
Edit: to address the question at the bottom that I missed, multiple things could be wrong. One may be that you dont have any data in the database. Or the where clause is executed and none of your data fits the criteria. Check your database. We can't help with that.

Where clause in SQLite not working in android :(

I'm getting an annoying error when trying to query some data in SQLite.
Here is my code:
Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +" = "+compareToThis, null, null, null, null);
I'm just returning the cursor as a string.
The error is saying:
no such column: compareToThis: while compiling.....the statement
My question is: why is SQLite setting the compareToThis attribute as a column when it's just a value?
How can I fix this?
Thanks in advance.
Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +" = ?", new String[]{compareToThis}, null, null, null);
The selection must include placeholder for parameter, and the next argument should be the array of parameters.
The solution by Vladimir works, however if you are like me and wonder why your approach did not work initially when it should have, here is why:
It is because it expects an integer unless you used (single or double) quotation marks to indicate that it is a string.
For example, in MySql this would return no results:
SELECT * FROM clients WHERE firstName = Bob; -- This will not work.
However when you surround it with quotations, it will return a result because it identifies Bob as a String literal.
Select * FROM clients WHERE firstName = 'Bob'; -- Single quotes work.
Select * FROM clients WHERE firstName = "Bob"; -- Double quotes as well.
Therefore for it to work, you would have to surround your compareToString with single quotes, as Muhhammad mentioned within the comments.
Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +'" = "+compareToThis+"'", null, null, null, null);

Categories

Resources