问题
This is on my selectedDayChange on my mainactivity.java
date= year +""+ month +""+ dayOfMonth;
allfood food = new allfood();
food.Date="DATE_"+date;
double a = repo.totalFat(food);
Toast.makeText(getApplicationContext(), "" +a, Toast.LENGTH_LONG).show();
While this is on my repo.java
public double totalFat(allfood date){
SQLiteDatabase db = dbHelper1.getReadableDatabase();
String query = "SELECT SUM(Fat) FROM " +allfood.TABLE+ " WHERE " +KEY_Date+"="+date;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
double i=c.getDouble(0);
return i;
}
Then it shows an error, by the way, I know I needed to make something like this: KEY_Date+"='"+date+"'"
String query = "SELECT SUM(Fat) FROM " +allfood.TABLE+ " WHERE " +KEY_Date+"='"+date+"'";
android.database.sqlite.SQLiteException: near ".": syntax error (code 1): , while compiling: SELECT SUM(Fat) FROM allfood WHERE Date=info.androidhive.navigationdrawer.Overall.allfood@1cbb35e1
This line
Date=info.androidhive.navigationdrawer.Overall.allfood@1cbb35e1
should be
Date=DATE_20170213
How can I fix this?
回答1:
1) Don't add a literal allfood
object to a String. SQL can't interpret a Java object.
The method should be any of the following because allfood
is the whole object, you do need it as the parameter. And naming it as date
is simply confusing.
totalFat(Date date)
totalFat(String date)
totalFat(Calendar date)
totalFat(int year, int month, int dayOfMonth)
should be
Date=DATE_20170213
2) No, it really shouldn't because Sqlite does not support that format of dates. Additionally, pre-pending DATE_
is just wasting storage in your database.
3) Please do not use this
date= year +""+ month +""+ dayOfMonth
Build a Calendar
object and use SimpleDateFormat
to correctly get a date formatted string.
using the last option above, you'd have something like this
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth);
String queryForDate = fmt.format(calendar.getTime());
// db.query(TABLE_NAME, null, new String[] {... // TODO: Complete this
来源:https://stackoverflow.com/questions/42204697/sqliteexception-using-where-key-date-date