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?
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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With