重写 SQLite 语句 SELECT WHERE - Android Eclipse
Posted
技术标签:
【中文标题】重写 SQLite 语句 SELECT WHERE - Android Eclipse【英文标题】:Rewrite SQLite statement SELECT WHERE - Android Eclipse 【发布时间】:2016-09-10 18:21:26 【问题描述】:我编写了一种方法,可以搜索数据库以根据模块查找匹配的讲师。但是,当我运行它时,它会为所有三个保存相同的名称!
方法如下:
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");
我知道我正在保存相同的“session.modulelecturer.toString();”每个人,但我不知道如何改变 SQL 方法来为所有三个单独的模块选择所有三个讲师。
【问题讨论】:
【参考方案1】:尝试替换
" 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 + "')";
【讨论】:
出于某种原因,这仍然会为所有三位讲师返回相同的姓名! :( 那么您为所有 3 个变量传递相同的值。您的查询中有一个错误,这让我眼前一亮,我修复了它。现在在某个地方出现了另一个错误。以上是关于重写 SQLite 语句 SELECT WHERE - Android Eclipse的主要内容,如果未能解决你的问题,请参考以下文章