1

我必须根据传递的参数获取数据库的行

例如,选择所有按姓名排序的 38 岁,并且是艺术家女性的人,传递的参数是

String age=38;
String gender=female;
String job=artist;

我试过写这个,但我的 rawQuery 肯定有语法错误

public Cursor getData(String age, String gender, String job) {
        try {
            Cursor c = mDb.rawQuery("SELECT * FROM mytable order by Name asc WHERE Age='"+age+"'"  WHERE Gender='"+gender+"'" WHERE Job='"+job+"'", null);
            if (c != null) {
                c.moveToNext();
            }
            return c;
        } catch (SQLException mSQLException) {
            Log.e(TAG, "getData>>" + mSQLException.toString());
            throw mSQLException;
        }

    }

有人可以帮我解决吗?

4

3 回答 3

2

如果 Age 是 String 类型,请尝试:

Cursor c = mDb.rawQuery("SELECT * FROM mytable WHERE Age LIKE \""+age+"\" AND Gender LIKE \""+gender+"\" AND Job LIKE \""+job+"\" order by Name asc", null);

如果 Age 是 Integer 类型,请尝试:

Cursor c = mDb.rawQuery("SELECT * FROM mytable WHERE Age = \""+age+"\" AND Gender LIKE \""+gender+"\" AND Job LIKE \""+job+"\" order by Name asc", null);

问候。

于 2012-11-30T01:22:28.520 回答
2

您的 SQL 语法中有多个错误。ORDER BY 子句应该放在最后。多个条件应该由 AND 关键字连接,而不是多个 WHERE。最后,您的报价没有正确匹配。

下面是正确的 SQL 查询:

SELECT * FROM mytable WHERE Age LIKE '"+age+"' AND Gender LIKE '"+gender+"' AND Job LIKE '"+job+"' ORDER BY Name ASC;

于 2012-11-30T01:25:18.970 回答
1

rawQuery("SELECT * FROM mytable WHERE ( Age = ? and Gender = ? and Job= ? ) order by Name asc",new String[]{age,gender,job})

于 2012-11-30T01:25:22.603 回答