SQLite查询获取列数据

时间:2016-07-22 09:22:41

标签: android sqlite

使用以下查询获取列数据:

public String getR(String str) {

    String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";

    return strR;
}

活动中,我正在尝试读取返回strR

    String string = mydb.getR("1400");
    Toast.makeText(SyncAll.this, string, Toast.LENGTH_SHORT).show();

但是在 Toast 中,我是getting我的选择查询本身而不是Record,如下所示:

SELECT col_no FROM tracking where col_id = '1400' ORDER BY col_no DESC LIMIT 1

我可以知道!我在哪里做错了?

2 个答案:

答案 0 :(得分:1)

我尝试了上面的繁荣k建议的相同方式,最后得到了解决方案:

public String getR(String str) {

    String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(strR, null);

    if (cursor != null)
        cursor.moveToFirst();

        strR = cursor.getString(0);

    return strR;
}

答案 1 :(得分:0)

您正在调用函数getR,它返回字符串值strR。

我假设mydb是来自SQLiteOpenHelper类的扩展对象,并且您已按照此处的文档https://developer.android.com/training/basics/data-storage/databases.html进行操作,那么您必须执行以下查询:

    Cursor cursor = null;
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        synchronized(this) {
            cursor = db.rawQuery(query, null);
            if (cursor.moveToFirst()) {
                col_no = cursor.getInt(0);
            }

        }
    } finally {
        if (null != cursor)
            cursor.close();
    }
    return col_no;