0

我正在开发一个家庭作业待办事项应用程序,我想在家庭作业旁边显示教授的联系信息。每个作业都有一个类 ID 值,它是类表的外键,它具有教授表的外键,其中包含我正在寻找的信息。我觉得这段代码应该可以工作,但它没有返回任何结果。

这是查询代码:

字符串 selectQuery = "SELECT " + KEY_CLASS_PROF +" FROM " + TABLE_CLASS + " , " + TABLE_ASSGN + " WHERE " + KEY_CLASS_ID + " = " + KEY_ASSGN_CLASS + " AND "+ KEY_ASSGN_ID + " = " + assgn_id;

  Log.d(LOG, selectQuery);

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);

    if (c == null)
      Log.d(LOG,"c is null! Why is c null?");

  if (c != null && c.moveToFirst()) {

      Log.d(LOG,"Cursor" + c.getPosition());

      thisProf = c.getInt(c.getColumnIndex(KEY_CLASS_PROF));

      Log.d(LOG,"thisProf is " + thisProf);


    } else Log.d(LOG,"returned null!");

和结果日志:

11-12 21:51:14.508: D/DatabaseHelper(622): SELECT * FROM ClassTable , AssignmentTable WHERE classid = fk_classid AND assignmentid = 2

11-12 21:51:14.508:D/DatabaseHelper(622):返回 null!

所以 c 不为空,但 (c != null && c.moveToFirst()) 返回 false。这真让我抓狂。任何帮助表示赞赏。

编辑:我想通了,结果返回了 0 个结果,所以即使 c 不为空,c.moveToFirst() 也是假的,因为没有第一个结果可以移动!

4

2 回答 2

1

您应该更改查询语法并使结果如下所示:

SELECT * FROM ClassTable C join AssignmentTable A ON C.classid =
A.fk_classid  WHERE assignmentid = 2
于 2013-11-13T03:12:03.667 回答
0

一个对象不能既是null又不是null,那是不可能的。让我们看看你的逻辑:

Cursor c = db.rawQuery(selectQuery, null); //you initialize the query (it isn't null now)

if (c == null) //right here you are checking if it is null or not


if (c != null && c.moveToFirst()) {

   //right here you have checked to make sure it isn't null AND that the
   //cursor found your query

} else Log.d(LOG,"returned null!");
   //this executes if either c == null or c cannot move to the first item (which
   //means that your query was either wrong, or turned up no results. if c was
   //actually null, your check at the top would evaluate true.

您只是误解了什么c.moveToFirst()意思(它找到了您查询的内容)。游标不能为空并且仍然什么也没有找到,只有当你从未初始化它时它才为空。由于您的中间 if 语句永远不会执行,您的第一个语句也不会执行,因此您知道 c 不为空,但您的查询变为空且 c 无法移动到第一个,因为它无处可去(因为您的查询变为空) .

我希望这能澄清你所看到的。您正在查询的数据不存在,或者您查询不正确,发布的其他答案应该可以帮助您解决。

于 2013-11-13T03:45:33.403 回答