开发者

sql query with WHERE

i am开发者_Go百科 trying to implement a detabase query using WHERE, and really just wondering how to implement it? the code i have here gives me an error ;/ thnánk you!

        public Cursor fetchAllCatagoryForSign(String sign) {
        String signSelect="";
        if(sign!=null){
            signSelect=" WHERE " + CATAGORY_SIGN + "=" + sign;
        }
        return mDb.rawQuery("SELECT " + CATAGORY_ID + "," +
                " " + CATAGORY_NAME +  "," +
                " " + CATAGORY_SIGN + " FROM "
                + CATAGORY_TABLE + signSelect + 
                " ORDER BY " + CATAGORY_NAME + " DESC", null);
    }


Please provide your error. You could try to switch to:

String.format(" WHERE %s = '%s'", CATEGORY_SIGN, sign);

String.format("SELECT %s, %s, %s, %s FROM %s %s ORDER BY %s DESC, null, CATEGORY_ID, CATEGORY_NAME, CATEGORY_SIGN, CATEGORY_TABLE, signSelect, CATEGORY_NAME);

I think this is a bit cleaner, even though you could format it better in your IDE.


If sign is a string related to a TEXTual (e.g. varchar) column, you would need quotes around it in most DBMS.

public Cursor fetchAllCatagoryForSign(String sign) {
    String signSelect="";
    if(sign!=null){
        signSelect=" WHERE " + CATAGORY_SIGN + "='" + sign.Replace("'","''") + "'";
    }
    return mDb.rawQuery("SELECT " + CATAGORY_ID + "," +
            " " + CATAGORY_NAME +  "," +
            " " + CATAGORY_SIGN + " FROM "
            + CATAGORY_TABLE + signSelect + 
            " ORDER BY " + CATAGORY_NAME + " DESC", null);
}

@updated following GolezTrol's note

If category sign comes from a user from the world at large, this pieces of code would be open to SQL injection, in which case, you would want to protect the "sign" variable using .Replace as shown in the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜