【问题标题】:SQLite rawQuery() with WHERE clause to return countSQLite rawQuery() 与 WHERE 子句返回计数
【发布时间】:2019-02-28 12:32:38
【问题描述】:

我有一个方法可以获取特定的字符串并将其搜索到 sqlite 数据库中。如果数据库中存在/不存在字符串,它应该返回 int count(行数),我该如何实现?

这是我针对该特定函数的代码,每次运行它都会返回零,即使指定的字符串存在于数据库中。

public int getMsgCount(String msgQuery) {
    String countQuery = "SELECT count(*) FROM " + MsgModal.TABLE_NAME + " WHERE " + MsgModal.COLUMN_MSG  + "= '" +msgQuery +"'";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.moveToFirst();
    int count = cursor.getInt(0);
    cursor.close();
    // return count
    return count;
}

【问题讨论】:

  • 这里没有什么特别错误的(除了潜在的 SQL 注入)——很可能 WHERE 不匹配任何行。您能否发布一些“指定字符串存在于数据库中”的证据
  • 感谢您的关注。我发现查询字符串中的错误,现在它工作正常。你能提供关于 SQL 注入的建议吗?
  • 使用?变量并将其值传递给selectionArgs,而不是将字符串放在SQL中。

标签: android sqlite


【解决方案1】:

查看此代码。

public int countRow(String query) {
    int count = 0;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    count = cursor.getCount();
    cursor.close();
    db.close();
    return count;
}

【讨论】:

    【解决方案2】:

    也许字符串是列的一部分,所以你需要LIKE而不是LIKE

    String countQuery = 
      "SELECT count(*) FROM " + MsgModal.TABLE_NAME + " WHERE " + MsgModal.COLUMN_MSG + " LIKE '%" + msgQuery + "%'";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多