0

我是 android 的菜鸟,我正在尝试查询一个 sqlite 表。我已经阅读了几个教程,并且知道如何查询表以返回一整列值,但我似乎无法弄清楚如何逐个字符串从列中查询单个值。任何帮助是极大的赞赏。这是我的代码:

我成功查询和返回整列值的代码:

public String getValue() {
        // TODO Auto-generated method stub
        String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_OUNCES, KEY_VALUE };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String result = "";

        int iRow = c.getColumnIndex(KEY_ROWID);
        int iName = c.getColumnIndex(KEY_NAME);
        int iQuantity = c.getColumnIndex(KEY_QUANTITY);
        int iOunces = c.getColumnIndex(KEY_OUNCES);
        int iValue = c.getColumnIndex(KEY_VALUE);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
            result = result + /*c.getString(iRow) + " " +*/ c.getString(iValue) + "\n";
        }           

    return result;
}

我尝试按字符串查询单个值的列:

public String getSingleValue(String aCoin) throws SQLException{
    // TODO Auto-generated method stub
    String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_OUNCES, KEY_VALUE};     
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + aCoin, null, null, null, null);
    String result = "";

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iQuantity = c.getColumnIndex(KEY_QUANTITY);
    int iOunces = c.getColumnIndex(KEY_OUNCES);
    int iValue = c.getColumnIndex(KEY_VALUE);

    if (c != null){
        c.moveToFirst();
        result= c.getString(1);
        return result;
    }
    return null;
}
4

1 回答 1

0

改变这个

   String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_OUNCES, KEY_VALUE };

        String[] columns = new String[]{ KEY_NAME};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + aCoin, null, null, null, null);
    String result = "";
   if (c != null){
        c.moveToFirst();
        result= c.getString(0);
        return result;
    }
    return null;

如果您只想获取名称列。

于 2012-08-29T01:03:30.900 回答