Android 中更新 SQLite 数据库的首选方法

4

在Android中,使用db.update的哪种方式更快、更好?即:构建包括where子句变量值的整个where子句字符串,还是利用update的第四个参数,通过传递where子句变量值作为一个字符串数组来更新?

通过将where子句变量值作为新字符串数组传递,是否可以防止SQL注入攻击?

  public boolean UpdateChannelSortKey(Channel c)
  {
        ContentValues cv = new ContentValues();
        cv.put("SortKey", c.SortKey);
        return this.db.update("Channels", cv, "ChannelID = ?", new String[]{String.valueOf(c.ChannelID)}) > 0;
  }

或者

public boolean UpdateChannelSortKey(Channel c)
  {
        ContentValues cv = new ContentValues();
        cv.put("SortKey", c.SortKey);
        return this.db.update("Channels", cv, "ChannelID = " + c.ChannelID, null) > 0;
  }
1个回答

8
第一种方法更可取,因为:
1)它可以防止SQL注入攻击。
2)最好总是使用预处理语句 - 不仅在Android中,这样你就会养成一个好习惯。
3)在我看来,它有更高的可读性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接