Java 如何检查SQL查询是否没有结果?
如标题所述,我使用以下方法检查我的SQL数据库:Java 如何检查SQL查询是否没有结果?,java,android,sql,Java,Android,Sql,如标题所述,我使用以下方法检查我的SQL数据库: public String[] getRecord(String category){ String[] record = new String[3]; Cursor crsRecord = sqliteDatabase.rawQuery(QUERY_GET_RECORD + category, null); int i=0; while(crsRecord.moveToNext(
public String[] getRecord(String category){
String[] record = new String[3];
Cursor crsRecord = sqliteDatabase.rawQuery(QUERY_GET_RECORD + category, null);
int i=0;
while(crsRecord.moveToNext()){
record[i] = crsRecord.getString(0);
i++;
}
return record;
}
现在可能是这样的:
Cursor crsRecord = sqliteDatabase.rawQuery(QUERY_GET_RECORD + category, null);
没有结果,因为我的数据库中没有适当的数据。我如何检查我没有结果
cursor.moveToFirst();
if (cursor.isAfterLast()){
// You have no results
}
或者,您可以将代码更改为:
while(!crsRecord.isAfterLast()){
// Instead of using an int literal to get the colum index,
// use the getColumnIndex method
int index = crsRecord.getColumnIndex(COLUMN_NAME);
if (index == -1) {
// You don't have the column-- do whatever you need to do.
}
else {
record[i] = crsRecord.getString(index);
i++;
}
crsRecord.moveToNext();
}
如果没有记录,while循环将永远不会启动。当我的数据库中甚至没有我要求的列时,会发生什么?然后我在游标行中得到了错误。或者,使用for循环习惯用法:
for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){