92

我想使用选择查询从表中检索数据。我找到了检索数据rawQuery(query, selectionArgs)的类方法。SQLiteDatabase但我不知道queryandselectionArgs应该如何传递给rawQuery方法?

4

7 回答 7

230
rawQuery("SELECT id, name FROM people WHERE name = ? AND id = ?", new String[] {"David", "2"});

您传递一个与“?”具有相同数量元素的字符串数组。

于 2012-05-15T09:50:05.687 回答
16

也许这可以帮助你

Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0) 
{               
    c.moveToFirst();
    do {
        id[i] = c.getInt(c.getColumnIndex("field_name"));
        i++;
    } while (c.moveToNext());
    c.close();
}
于 2012-05-15T10:05:12.940 回答
10

rawQuery 的一个例子——db.rawQuery("select * from table where column = ?",new String[]{"data"});

于 2012-05-15T09:48:59.353 回答
3

请参阅下面的代码,它可能会对您有所帮助。

String q = "SELECT * FROM customer";
Cursor mCursor = mDb.rawQuery(q, null);

或者

String q = "SELECT * FROM customer WHERE _id = " + customerDbId  ;
Cursor mCursor = mDb.rawQuery(q, null);
于 2012-05-15T09:51:17.203 回答
3

如果您的 SQL 查询是这样的

SELECT id,name,roll FROM student WHERE name='Amit' AND roll='7'

那么 rawQuery 将是

String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"} 
db.rawQuery(query, selectionArgs);
于 2018-03-09T07:01:36.457 回答
2

为了完整性和正确的资源管理:

        ICursor cursor = null;
        try
        {

            cursor = db.RawQuery("SELECT * FROM " + RECORDS_TABLE + " WHERE " + RECORD_ID + "=?", new String[] { id + "" });

            if (cursor.Count > 0)
            {
                cursor.MoveToFirst();
            }
            return GetRecordFromCursor(cursor); // Copy cursor props to custom obj
        }
        finally // IMPORTANT !!! Ensure cursor is not left hanging around ...
        {
            if(cursor != null)
                cursor.Close();
        }
于 2016-08-25T11:13:34.837 回答
0
String mQuery = "SELECT Name,Family From tblName";
Cursor mCur = db.rawQuery(mQuery, new String[]{});
mCur.moveToFirst();
while ( !mCur.isAfterLast()) {
        String name= mCur.getString(mCur.getColumnIndex("Name"));
        String family= mCur.getString(mCur.getColumnIndex("Family"));
        mCur.moveToNext();
}

姓名和家庭是你的结果

于 2016-06-26T10:52:29.850 回答