【发布时间】:2018-05-18 16:34:17
【问题描述】:
在这里,我需要从表'TABLE_NAME' 中获取结果,其中'COLUMN_NAME_COUNTRY' = country 'AND' 'COLUMN_NAME_CATEGORY' = local 'OR' NA (Na also a value in the 'COLUMN_NAME_CATEGORY'。以下是我的代码:
public List<AppDataBean>getAllDataForSelectedCountryWithCategory(String country){
ArrayList<AppDataBean>dataList= new ArrayList<>();
SQLiteDatabase db = AppDbHelper.getInstance(context).getWritableDatabase();
dataList.clear();
try {
Cursor c = db.rawQuery("SELECT * FROM " + AppDbConstructor.AppData.TABLE_NAME + " WHERE " + AppDbConstructor.AppData.COLUMN_NAME_COUNTRY + "='" + country + "'"
+ " AND " + AppDbConstructor.AppData.COLUMN_NAME_CATEGORY + "='" + "Local" + "'" + " OR " + AppDbConstructor.AppData.COLUMN_NAME_CATEGORY + "='" + "NA" + "'" , null);
if (c.getCount()>0)
{
if (c.moveToFirst())
{
for (int i=0; i<c.getCount(); i++)
{
AppDataBean appDataBean = new AppDataBean();
appDataBean.setCategory(c.getString(c.getColumnIndex(AppDbConstructor.AppData.COLUMN_NAME_CATEGORY)));
appDataBean.setUrl(c.getString(c.getColumnIndex(AppDbConstructor.AppData.COLUMN_NAME_URL)));
appDataBean.setSource(c.getString(c.getColumnIndex(AppDbConstructor.AppData.COLUMN_NAME_SOURCE)));
appDataBean.setIconUrl(c.getString(c.getColumnIndex(AppDbConstructor.AppData.COLUMN_NAME_ICON_URL)));
appDataBean.setCountry(c.getString(c.getColumnIndex(AppDbConstructor.AppData.COLUMN_NAME_COUNTRY)));
Log.d("APP_DB_SOURCE","COLUMN_NAME_SOURCE: "+ c.getString(c.getColumnIndex(AppDbConstructor.AppData.COLUMN_NAME_URL))
+ ", " + c.getString(c.getColumnIndex(AppDbConstructor.AppData.COLUMN_NAME_CATEGORY)));
dataList.add(appDataBean);
Log.d("APPDBSOURCE", "LIST_VALUES_ARE" + dataList.get(i).getCategory() + ", " + dataList.get(i).getCountry());
c.moveToNext();
}
}
}
c.close();
}catch (Exception e){
e.printStackTrace();
}
finally
{
db.close();
}
return dataList;
}
最终结果是“所有国家/地区”和“本地”类别。
【问题讨论】:
-
你遇到了什么问题?
-
可能您的所有国家都被标记为本地/NA。
-
你少了一个括号,因为
AND和OR的优先级不是你想的那样。大多数人都弄错了,所以最好在混合AND和OR时总是使用括号。你写了WHERE country = '...' AND category = 'Local' OR category = 'NA',意思是WHERE (country = '...' AND category = 'Local') OR category = 'NA',但你的意思是WHERE country = '...' AND (category = 'Local' OR category = 'NA')。更好的是,使用IN子句:WHERE country = '...' AND category IN ('Local', 'NA') -
非常感谢。它正在工作
标签: java android android-sqlite android-cursor android-query