问题描述
这是在我的mainactivity.java上的selectedDayChange上
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();
这是在我的repo.java上
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;
}
然后它显示一个错误,顺便说一句,我知道我需要做这样的事情:KEY_Date+"='"+date+"'"
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+"'";
此行
应该是
我该如何解决?
推荐答案
1)不要在字符串中添加文字allfood
对象. SQL无法解释Java对象.
1) Don't add a literal allfood
object to a String. SQL can't interpret a Java object.
该方法应为以下任意一种,因为allfood
是整个对象,因此确实需要它作为参数.并将其命名为date
简直令人困惑.
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)
totalFat(Date date)
totalFat(String date)
totalFat(Calendar date)
totalFat(int year, int month, int dayOfMonth)
2)不,它确实不应该,因为 Sqlite不支持该日期格式.此外,在前面加上DATE_
只是在浪费数据库中的存储空间.
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)请不要使用此
date= year +""+ month +""+ dayOfMonth
构建一个Calendar
对象,并使用SimpleDateFormat
正确获取日期格式的字符串.
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
这篇关于使用WHERE的SQLiteException"+ KEY_Date +"=""+ date +"“"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!