如何在sqlite中进行选择

时间:2013-12-18 21:06:07

标签: android sqlite

我希望看到一个球员名单,但只能来自一支球队。我可以在我的团队课上看到所有这样的球员:

List <Players> list = new ArrayList<Players>();
list=db.getAllPlayers();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listContent.setAdapter(adapter);

但我需要的是从team ='5'的团队中获取所有玩家。但是我该怎么做?这是我在sqlitehelper类中的getAllPlayers

public List<Players> getAllPlayers() {
        List<Players> speler = new LinkedList<Players>();

        String query = "SELECT  * FROM " + TABLE_SPELERS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query, null);



        Players spelers = null;
        if (cursor.moveToFirst()) {
            do {
             spelers = new Players();
             spelers.setIdSpeler(Integer.parseInt(cursor.getString(0)));
             spelers.setShirt(Integer.parseInt(cursor.getString(1)));
             spelers.setSpeler(cursor.getString(2));

               speler.add(spelers);
            } while (cursor.moveToNext());
        }

        Log.d("Alle spelers in DB:", speler.toString());

    return speler;
    }

那么有没有办法改变字符串查询?

1 个答案:

答案 0 :(得分:3)

更改

String query = "SELECT  * FROM " + TABLE_SPELERS;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);

类似

String query = "SELECT  * FROM " + TABLE_SPELERS + " WHERE team=?";

SQLiteDatabase db = this.getWritableDatabase();
String[] selectionArgs = new String[] { "5" };
Cursor cursor = db.rawQuery(query, selectionArgs);

WHERE指定标准SQL选择。 ?是一个占位符,其中文字将从selectionArgs绑定。

编辑添加:要从调用方法设置选择参数,只需添加方法参数,例如

public List<Players> getPlayersForTeam(int teamNumber) {
    // ...
    String[] selectionArgs = new String[] { Integer.toString(teamNumber) };

并将其称为list = getPlayersForTeam(5);