【问题标题】:How does whereClause work in public int delete (String table, String whereClause, String[] whereArgs);whereClause 如何在 public int delete (String table, String whereClause, String[] whereArgs) 中工作;
【发布时间】:2014-04-03 12:00:01
【问题描述】:

所以我试图通过传递指定行的 id 从我的数据库中删除一个行,我在网上找到了一些代码,但我真的不知道它是如何工作的。它使用 SQLiteDatabase 的 db.delete 方法中的 whereClause 参数。有人知道它背后的逻辑吗? getWhereClause 究竟做了什么?

 //the delete method in my database class
 public void deleteRow(String compareColumn, String compareValue) {
    // ask the database manager to delete the row of given id
    try {
        String whereClause = getWhereClause(compareColumn, compareValue);
    db.delete(TABLE_NAME, whereClause, null);
        //db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);
    } catch (Exception e) {
        Log.e("DB DELETE ERROR", e.toString());
        e.printStackTrace();
    }
}

  //the method that returns whereClause
private String getWhereClause(String compareColumn, String compareValue) {
    String whereClause = null;
    if (compareColumn == null || compareColumn == "") { }
    else if (compareValue == null || compareColumn == "") { }
    else { whereClause = compareColumn + "=\"" + compareValue + "\""; }
    return whereClause;

【问题讨论】:

    标签: java android database sqlite sql-delete


    【解决方案1】:

    delete() 使用传入的whereClause 来构造类似DELETE FROM <tablename> WHERE <whereClause> 的SQL 语句。如果传入的whereClausenull,则省略WHERE <whereClause> 并删除所有行。

    您的getWhereClause() 构造了一个可用作whereClause 的表达式,将列与指定的字符串文字值进行比较,例如foo="bar"。如果其中一个为 null 或为空,则返回 null whereClause,以便匹配所有行。

    【讨论】:

      【解决方案2】:

      简单来说,它需要两个参数

      1.列名

      2.列值

      并创建一个String 文字并返回它。例如“student_id=100”,其中列名是student_id,column_value 是100。当两个参数中的任何一个为空时,它返回null

      【讨论】:

        【解决方案3】:

        它只检查参数是否为非null/非空并返回WHERE 条件的语句,如下所示:message = "Superman"。所以结果查询会是这样的:DELETE FROM myTable WHERE message = "Superman"

        顺便说一句,既然是字符串字面量,最好用单引号代替双引号,比如whereClause = compareColumn + "='" + compareValue + "'"

        【讨论】:

          【解决方案4】:

          方法deleteRow() 获取列(类似于“名称”)和值(类似于“Lukas”):

          public void deleteRow(String compareColumn, String compareValue) 
          

          String 变量 whereClause 使用 getWhereClause(column, value)- 方法在 SQL where 子句(如 (WHERE name LIKE "Lukas") 中形成两个 String 变量。

          现在对象db.delete() 方法将变量whereClause 作为参数并执行删除查询。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-06-19
            • 2020-03-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-05-03
            • 2017-06-02
            • 2019-08-12
            相关资源
            最近更新 更多