我有两张主题和章的表格。我需要通过传递 chapter_name 的 Subject_id 即可。我的问题是如何做到这一点?当我传递值时,id不返回任何内容 请给出一些提示 这是我的代码供参考。
public List<ObjectiveWiseQuestion> getAllChapter(long subId)
{
List<ObjectiveWiseQuestion>LocwiseProfileList=new ArrayList<ObjectiveWiseQuestion>();
String selectQuery=("select chapterName from chapter where subject_id ='"+ subId +"'");
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst())
{
do {
ObjectiveWiseQuestion owq= new ObjectiveWiseQuestion();
owq.setChapterName(cursor.getString(2));
LocwiseProfileList.add(owq);
} while(cursor.moveToNext());
db.close();
}
return LocwiseProfileList;
}
它还显示 illegalState 异常。
答案 0 :(得分:1)
将您的代码更改为:
public List<ObjectiveWiseQuestion> getAllChapter(long subId)
{
List<ObjectiveWiseQuestion>LocwiseProfileList=new ArrayList<ObjectiveWiseQuestion>();
String selectQuery=("select chapterName from chapter where subject_id =?");
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[]{subId}); // The secure way of executing raw queries
if (cursor.moveToFirst())
{
do {
ObjectiveWiseQuestion owq= new ObjectiveWiseQuestion();
//Get column index like this
owq.setChapterName(cursor.getString(cursor.getColumnIndexOrThrow("subject_id")));
LocwiseProfileList.add(owq);
} while(cursor.moveToNext());
cursor.close();
db.close();
}
return LocwiseProfileList;
}
我已将您的查询更改为使用安全方式。
此外,不应使用cursor.getString(0)或cursor.getString(2) 。因为sqlite文档声明查询结果不必具有与创建表时间相同的顺序列。这有时会给你错误但不是每次都有错误
答案 1 :(得分:0)
变化:
owq.setChapterName(cursor.getString(2));
到此:
/* read value from first column (chapterName) i.e. at index 0 */
owq.setChapterName(cursor.getString(0));
并且不要忘记在关闭数据库之前关闭光标:
cursor.close();
db.close();