所以我试图通过传递指定行的 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;
delete()
使用传入的whereClause
来构造一个像DELETE FROM <tablename> WHERE <whereClause>
这样的SQL语句。如果传入的whereClause
null
,则省略WHERE <whereClause>
并删除所有行。
您的getWhereClause()
构造一个可用作whereClause
的表达式,将列与指定的字符串文本值进行比较,如 foo="bar"
。如果其中一个为 null 或为空,则返回 null whereClause
,以便匹配所有行。
简单地解释一下, 它需要两个参数
1.列名
2.列值
并创建一个String
文本并将其返回。例如,假设"student_id=100",其中列名是student_id
,column_value是100
。当两个参数中的任何一个为 null 时,它将返回null
它只是检查参数是否为非null
/非空,并返回WHERE
条件的语句,如下所示:message = "Superman"
.因此,结果查询将如下所示:DELETE FROM myTable WHERE message = "Superman"
顺便说一句,由于它是字符串文字,因此最好使用单引号而不是双引号,就像这样whereClause = compareColumn + "='" + compareValue + "'"
方法deleteRow()
获取列(如"名称")和值(如"Lukas"):
public void deleteRow(String compareColumn, String compareValue)
字符串变量whereClause
使用 getWhereClause(column, value)
- 方法在 SQL where 子句中格式化这两个字符串变量,如 ( WHERE name LIKE "Lukas"
)。
现在,对象db
的.delete()
方法将变量whereClause
作为参数并执行删除查询。