Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite strange behavior

I want to retrieve a particular cell from a table. I want alarm_music(TEXT) where I have the hours(INTEGER) and the minutes(INTEGER)(In the where clause) of the alarm stored in the alarm table.
code where the query is fired

mBhelperClass = new AlarmsDBhelperClass(this);
        db= mBhelperClass.getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT musicPath FROM alarms WHERE hours="+hour+" AND minutes="+min,null);
        Log.d("gaurnagSnooze",""+cursor.getCount());
        if (cursor.moveToFirst()) {
            songPath = cursor.getString(cursor.getColumnIndex(AlarmsDBhelperClass.MUSIC_PATH));
            Log.d("if executed! ","songpath initialized!");
        }
        cursor.close();

the moveToFirst() returns FALSE meaning no rows in the table.
but when I fire SELECT musicPath FROM alarms the moveToFirst() returns TRUE.
how is this possible?

like image 359
Raunak Pandey Avatar asked Feb 29 '20 04:02

Raunak Pandey


2 Answers

Problem: The cursor.moveToFirst() returned FALSE meaning no Rows existing.

Solution: While inserting rows in the table I used a 24hour clock format Calendar's instance from the time picker and stored in the table. But when I tried to retrieve the value from the database using hours as the where clause I used 12Hour clock format Calendar's instance. which would for sure yield no output hence no rows returned as cursor and cursor.moveToFirst() returning FLASE.

like image 53
Raunak Pandey Avatar answered Nov 14 '22 00:11

Raunak Pandey


This query is unsafe it may result on unwanted result. However, if you want to use unsafe mode change below query

"SELECT musicPath FROM alarms WHERE hours="+hour+" AND minutes="+min

To

"SELECT musicPath FROM alarms WHERE hours= '"+hour+"' AND minutes= '"+min+"'"

add ' around the whereArgs.

Although it's correct but it's not recommended(unsafe)

it's recommended(safe) to include ? in where clause in the query and replace them by values from where args.

Cursor cursor = db.rawQuery("SELECT musicPath FROM alarms WHERE hours = ? AND minutes = ? ",new String[]{hour,min});
like image 26
A Farmanbar Avatar answered Nov 14 '22 01:11

A Farmanbar