在Android中使用rawQuery和rowid从sqlite数据库中选择一行 [英] Selecting one row from sqlite database using rawQuery and rowid in Android

查看:424
本文介绍了在Android中使用rawQuery和rowid从sqlite数据库中选择一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类似于以下内容的外部SQLite数据库:

I've created an external SQLite database that looks something like this:

我要在Android应用程序中执行的操作是使用ROWID从一行加载所有值并将它们放入数组.例如:

What I want to do in my Android application is to load all the values from one row using ROWID and put them into array. For example:

Cursor cursor = db.rawQuery("SELECT * FROM Dairy WHERE ROWID = 1", null);

这将返回第1行的所有值:51、35、63.但是,它始终仅返回第一个值,在本例中为51.而且,cursor.getCount()始终返回1. 这是我完整的代码:

This would return all the values from row 1: 51, 35, 63. However, this always returns just first value, in this case 51. Also, the cursor.getCount() always returns 1. Here's my complete code:

db = getReadableDatabase();

Cursor cursor = db.rawQuery("SELECT * FROM Dairy WHERE ROWID = 1", null);

yData = new int[cursor.getCount()];

if (cursor.moveToFirst()) {
    for (int i = 0; i < cursor.getCount(); i++) {
        yData[i] = cursor.getInt(0);
        cursor.moveToNext();
    }
    cursor.close();
}
db.close();

感谢您的帮助.

推荐答案

如果我正确理解,您需要从单行中返回每一列的值.由于您只选择单行,并且希望从每一列中获取价值,因此只需要获取每一列的索引即可.然后遍历它们.这是代码的实现方式.

If I correctly understand you need to return value of every column from the single row. Since you select only single row and want to get value from every column you need only to get the index of every column. and next iterate through them. Here is the code how it can be done.

Cursor cursor = db.rawQuery("SELECT * FROM Dairy WHERE ROWID = 1 Limit 1", null);

    if (cursor.moveToFirst()) {

    String[] columnNames = cursor.getColumnNames();

     yData = new int[columnNames.length];

        for (int i = 0; i < columnNames.length; i++) {

            // Assume every column is int

            yData[i] = cursor.getInt(cursor.getColumnIndex(columnNames[i]));
        }

    }
    cursor.close();
    db.close();

这篇关于在Android中使用rawQuery和rowid从sqlite数据库中选择一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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