Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare sqlite with string

Tags:

android

sql

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 ?

like image 915
user1750720 Avatar asked Dec 16 '22 18:12

user1750720


2 Answers

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

like image 172
dorjeduck Avatar answered Jan 02 '23 05:01

dorjeduck


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();
    }
}
like image 24
Darwind Avatar answered Jan 02 '23 03:01

Darwind