我编写了一种搜索数据库的方法,根据模块查找匹配的讲师。但是,当我运行它时,它会为所有三个保存相同的名称!
以下是方法:
public List<tableModules> getStudentsLecturers(String mod1, String mod2, String mod3) {
List<tableModules> studentModuleLecturer = new ArrayList<tableModules>();
// Select All Query to find lecturers depending on modules
Log.d("Lecturers", mod1);
Log.d("Lecturers", mod2);
Log.d("Lecturers", mod3);
String selectQuery = "SELECT DISTINCT " + Module_Lecturer + " FROM " + Table2 + " WHERE " + Module_Name + " = \'" + mod1 + "\' OR \'" + mod2 + "\' OR \'" + mod3 + "\'";
Log.d("1", "1");
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableModules moduleLecturers = new tableModules();
moduleLecturers.modulelecturer = cursor.getString(0);
studentModuleLecturer.add(moduleLecturers);
} while (cursor.moveToNext());
}
// return lecture list
return studentModuleLecturer;
}
然后在 MainActivity.java
中调用List<tableModules> lecturers = db.getStudentsLecturers(mod1, mod2, mod3);
if (!lecturers.isEmpty())
{
for (tableModules session: lecturers)
{
Editor editor = preferences.edit();
//Save lecturers to list
for (int i=0; i < lecturers.size(); i++) {
if (counter == 0)
{
lecturer1 = session.modulelecturer.toString();
editor.putString("lec1", lecturer1);
Log.d("Lecs", "1");
editor.commit();
counter++;
}
if (counter == 1)
{
lecturer2 = session.modulelecturer.toString();
editor.putString("lec2", lecturer2);
Log.d("Lecs", "2");
editor.commit();
counter++;
}
if (counter == 2)
{
lecturer3 = session.modulelecturer.toString();
editor.putString("lec3", lecturer3);
Log.d("Lecs", "3");
editor.commit();
counter++;
}
else
{
Log.d("Lecs", "ERROR");
}
}
我得到了我保存相同的&#34; session.modulelecturer.toString();&#34;对于每一个,但我无法弄清楚如何改变SQL方法来为所有三个单独的模块选择所有三个讲师。
答案 0 :(得分:2)
尝试替换
" WHERE " + Module_Name + " = \'" + mod1 + "\' OR \'" + mod2 + "\' OR \'" + mod3 + "\'";
与
" WHERE " + Module_Name + " = '" + mod1 + "' OR " + Module_Name + " = '" + mod2 + "' OR " + Module_Name + " = '" + mod3 + "'";
在实践中,你不能说
WHERE ModuleName = 'This' OR 'That'
但你可以说
WHERE ModuleName = 'This' OR ModuleName = 'That'
我知道为每个可能的值重写列名是一种拖累,但它是如何在SQL中工作的。
或者,您可以编写更紧凑的表单:
WHERE ModuleName IN ('This', 'That', '...')
所以你的查询可以变成:
" WHERE " + Module_Name + " IN ('" + mod1 + "', '" + mod2 + "', '" + mod3 + "')";