Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 从SQLite返回一个int结果_Android_Sqlite - Fatal编程技术网

Android 从SQLite返回一个int结果

Android 从SQLite返回一个int结果,android,sqlite,Android,Sqlite,所以我想找到max ID并通过添加1返回它 以下是我在SQLhelper中的代码。它看起来非常错误,因为它在中为public void,但我返回了CR。我有点困惑,因为游标用于读取记录,但我只希望使用SQL查询返回integer的结果 public int getID( String name){ String idquery="SELECT IFNULL(MAX(id),0)+1 FROM "+TableInfo.TABLE_NAME+ " WHERE appliance="+nam

所以我想找到max ID并通过添加1返回它

以下是我在SQLhelper中的代码。它看起来非常错误,因为它在中为public void,但我返回了CR。我有点困惑,因为游标用于读取记录,但我只希望使用SQL查询返回integer的结果

 public int getID( String name){
    String idquery="SELECT IFNULL(MAX(id),0)+1 FROM "+TableInfo.TABLE_NAME+ " WHERE appliance="+name;
    SQLiteDatabase SQ=this.getReadableDatabase();
    Cursor CR=SQ.rawQuery(idquery,null);
    return CR;
}
这是我从另一个活动中所说的

int no_id=DB.getID(name);
有人请帮帮我。谢谢。

你必须像这样做:

public int getID( String name){

    String idquery="SELECT IFNULL(MAX(id),0)+1 FROM "+TableInfo.TABLE_NAME+ " WHERE appliance="+name;

    SQLiteDatabase SQ=this.getReadableDatabase();
    Cursor CR=SQ.rawQuery(idquery,null);


     int id = -1;

     if (CR != null && CR.getCount() > 0) {
         CR.moveToFirst();
         id = CR.getInt(c.getColumnIndex(YOUR_COLUMN_NAME));
         CR.close();
     }
     return id;
}
编辑:

将查询中的列
IFNULL(MAX(id),0)+1更改为maxcount
IFNULL(MAX(id),0)+1,然后您可以在从光标获取值时将其指定为:

id = CR.getInt(c.getColumnIndex("maxcount"));
它将返回您想要的整数

希望它能帮助你。

试试这个

public int getMaxID(){
    int maxID = 0;

    String selectQuery = "SELECT "+here you primary key name +" FROM " + TableInfo.TABLE_NAME;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do{
            maxID = cursor.getInt(0);

        }while(cursor.moveToNext());
    }
    return cursor.getCount();
}

如果
name
是字符串值,则必须在SQL中引用它。但更好的方法是使用参数

要从查询中读取单个数字而不必使用光标,有一个有用的方法:

intgetid(字符串名称){
SQLiteDatabase db=getReadableDatabase();
return(int)DatabaseUtils.longForQuery(db,
选择IFNULL(最大值(id),0)+1+
“FROM”+TableInfo.TABLE\u名称+
“其中设备=?”,
新字符串[]{name});
}

返回前,访问光标检查是否有行。如果有,请访问第一列以通过CR.getInt(0)检索ID,假定它是唯一的列,因此它将是索引0。返回检索到的值,而不是整个游标。此行的作用是“id=CR.getInt(c.getColumnIndex(您的_COLUMN_NAME));”?因为返回的结果没有任何列。将
IFNULL(MAX(id),0)+1作为maxcount
并将其作为列名,这意味着我有一个名为maxcount的列,它接受
IFNULL(MAX(id),0)+1
?我可以简单地执行查询并将其值带入函数吗?是的,,,并且必须作为列名传递。我可以简单地执行查询并将其值带入函数吗?