如何使用游标查询从sqlite数据库中检索值? [英] how to retrieve value from sqlite database using cursor query?

查看:171
本文介绍了如何使用游标查询从sqlite数据库中检索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表'balance_table'中插入了一行。



  //   insert: 
public long insertinBalance( String new_bal1){
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentvalues = new ContentValues();
contentvalues.put(VivzHelper.AVL_BALANCE,new_bal1);
long id = db.insert(VivzHelper.BALANCE_TABLE,null,contentvalues);
helper.close();
return id;
}

// 检索列值

public 游标余额(){
SQLiteDatabase db = helper.getReadableDatabase();
String [] columns = {VivzHelper.BAL_UID,VivzHelper.AVL_BALANCE};
Cursor c1 = db.query(VivzHelper.BALANCE_TABLE,columns,null,null,
null,null,null);
existing_bal = 0;
if (c1.getCount()> 0 ){
existing_bal = (c1.getString( 1 ));
}
else
{
}
helper.close();
return c1;





我想检索值从列'avl_balance'并使用上面的代码传递给变量'existing_bal'。我在logcat中得到错误,如下所示:引起:android.database.CursorIndexOutOfBoundsException:索引-1请求,大小为1

如何纠正以将值传递给变量'existing_bal'。 div class =h2_lin>解决方案

  if (c1.getCount()>  0 ){
existing_bal =(c1.getString( 1 ));
}



应该是

  if (c1.getCount()>  0 ){
existing_bal =(c1.getString( 0 )); // 第一个元素是索引零
}





请参阅 http ://developer.android.com/reference/android/database/Cursor.html#getString(int) [ ^ ]。


I have inserted row into the table 'balance_table'.

//insert:
 public long insertinBalance(String new_bal1) {
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues contentvalues = new ContentValues();
        contentvalues.put(VivzHelper.AVL_BALANCE, new_bal1);
        long id = db.insert(VivzHelper.BALANCE_TABLE, null, contentvalues);
        helper.close();
        return id;
    }

// retrieve column value

 public Cursor balance() {
        SQLiteDatabase db = helper.getReadableDatabase();
        String[] columns = {VivzHelper.BAL_UID, VivzHelper.AVL_BALANCE}; 
        Cursor c1 = db.query(VivzHelper.BALANCE_TABLE, columns,null , null, 
        null,null,null);
        existing_bal = "0";
        if(c1.getCount() > 0){
            existing_bal = (c1.getString(1));
        }
        else
        {
        }
        helper.close();
        return c1;



I wanted to retrieve the value from column 'avl_balance' and pass into a variable 'existing_bal' using the above code. I get error in logcat stating like:Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
How to rectify to get the value passed into variable 'existing_bal'.

解决方案

if(c1.getCount() > 0){
    existing_bal = (c1.getString(1));
}


should be

if(c1.getCount() > 0){
    existing_bal = (c1.getString(0)); // first element is index zero
}



See http://developer.android.com/reference/android/database/Cursor.html#getString(int)[^].


这篇关于如何使用游标查询从sqlite数据库中检索值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆