Sqlite验证列的值是否存在 [英] Sqlite verify if value of column exists

查看:211
本文介绍了Sqlite验证列的值是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这个方法是否正确验证_username的值是否已经在username列中存在

i'm wondering if this method is right to verify if the value of _username already exists in the column "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"
}

有没有更好的方法做同样的事情,我真的不知道这个,它似乎对我来说。
谢谢。

Is there a better way to do the same thing, i'm really not sure about this, it seemed right for me. Thanks.

推荐答案


有更好的方法做同样的事情,我真的不知道
这个,它似乎对我来说。感谢。

Is there a better way to do the same thing, i'm really not sure about this, it seemed right for me. Thanks.

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

In the terms of security and purity yes, for sure.

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完成工作时,请释放它。

I recommend you to an usage of ? that is called placeholder. Each placeholder will be replaced with value from string array in the same order. This is called also parametrized statement as a defence agains SQL injection. When your work with Cursor is finished, release it.

这篇关于Sqlite验证列的值是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆