Sqlite验证列的值是否存在

时间:2013-03-23 16:04:07

标签: android sqlite select cursor

我想知道这种方法是否适合验证_username的值是否已存在于“username”列中

public boolean verification(String _username) throws SQLException{
    Cursor c = dataBase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+KEY_USERNAME+"="+_username, null);
    if (c!=null)
        return true; // return true if the value of _username already exists
    return false; // Return false if _username doesn't match with any value of the columns "Username"
}

有没有更好的方法来做同样的事情,我真的不确定这一点,对我来说似乎是对的。 谢谢。

2 个答案:

答案 0 :(得分:6)

Beware的{p> SQL injection attacks!您应该始终使用参数化查询:

Cursor c = dataBase.rawQuery("SELECT 1 FROM "+TABLE_NAME+" WHERE "+KEY_USERNAME+"=?", new String[] {_username});

(老实说,我不确定你的第一个查询是如何抛出异常的,因为你忘了将字符串包装在引号中......)

同样rawQuery()将始终返回Cursor,您必须检查Cursor是否为空,而不是null


至于“最好的”方法,这很好用,但我建议关闭光标以释放资源。一起来:

public boolean verification(String _username) {
    Cursor c = dataBase.rawQuery("SELECT 1 FROM "+TABLE_NAME+" WHERE "+KEY_USERNAME+"=?", new String[] {_username});
    boolean exists = c.moveToFirst();
    c.close();
    return exists;
}

答案 1 :(得分:2)

  

有没有更好的方法来做同样的事情,我真的不确定   这对我来说似乎是对的。感谢。

在安全性和纯度方面是肯定的。

public boolean verification(String _username) throws SQLException {
    int count = -1;
    Cursor c = null; 
    try {
       String query = "SELECT COUNT(*) FROM " 
                   + TABLE_NAME + " WHERE " + KEY_USERNAME + " = ?"
       c = dataBase.rawQuery(query, new String[] {_username});
       if (c.moveToFirst()) {
          count = c.getInt(0);
       }
       return count > 0;
    }
    finally {
       if (c != null) {
          c.close();
       }
    }
}

我建议您使用名为占位符 ? 。每个占位符将以相同的顺序替换为字符串数组中的值。这也被称为参数化语句作为防御再次SQL注入。使用Cursor完成后,将其释放。