RawQuery (查询,selectionArgs)

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

193613 次浏览

One example of rawQuery - db.rawQuery("select * from table where column = ?",new String[]{"data"});

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

You pass a string array with an equal number of elements as you have "?"

see below code it may help you.

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

or

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

Maybe this can help you

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();
}
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();
}

Name and family are your result

For completeness and correct resource management:

        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();
}

if your SQL query is this

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

then rawQuery will be

String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"}
db.rawQuery(query, selectionArgs);