我正在做一个家庭作业待办事项应用程序,我想在家庭作业旁边显示教授的联系信息。每个赋值都有一个类ID值,它是类表的外键,它具有教授表的外键,该表具有我正在寻找的信息。我觉得这段代码应该可以正常工作,但它不会返回任何结果。
这是查询代码:
String 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不是null但是(c!= null&& c.moveToFirst())返回false。这真让我抓狂。任何帮助表示赞赏。
编辑:我想通了,结果是0结果被返回,所以即使c不为null,c.moveToFirst()也是假的,因为没有第一个结果要移动到!答案 0 :(得分:1)
您应该更改查询语法,并使结果如下所示:
SELECT * FROM ClassTable C join AssignmentTable A ON C.classid =
A.fk_classid WHERE assignmentid = 2
答案 1 :(得分: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不是null,但你的查询变为空,c无法移动到第一个,因为它无处可去(因为你的查询变为空)
我希望澄清你看到的一点。您查询的数据不存在,或者您查询错误,发布的其他答案应该可以帮助您解决。