在android中正确的SQLite查询语法

时间:2012-11-30 01:09:48

标签: android sqlite android-sqlite

我必须根据传递的参数

获取数据库的行 例如,选择所有按名称排序的人,年龄为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;
        }

    }

有人可以帮我解决吗?

3 个答案:

答案 0 :(得分:2)

如果Age是type 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);

问候。

答案 1 :(得分:2)

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

以下是正确的SQL查询:

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

答案 2 :(得分:1)

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