You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么SQLite select查询在Android Studio的Database Inspector正常但应用失效?

问题根因

  • 你在拼接带where条件的SQL语句时,没有为字符串类型的日期参数添加单引号,SQLite会将dd-MM-yyyy格式的日期识别为减法数值表达式,而非你要匹配的字符串值,导致查询无匹配结果。你在Database Inspector中执行查询时会主动给字符串参数加引号,所以能正常返回结果。
  • 直接拼接SQL参数还存在SQL注入风险,属于不规范的用法。

修复方案

推荐使用SQLite参数绑定的方式传参,避免手动处理引号问题,同时规避注入风险,修正后的代码如下:

public ArrayList<String> retrieveFunc() {
    ArrayList<String> array_list = new ArrayList<String>();
    SQLiteDatabase db = this.getReadableDatabase();
    String date = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
    // 使用?作为占位符,参数通过第二个字符串数组传入
    Cursor res =  db.rawQuery( "select score from stats WHERE date = ?", new String[]{date});
    if(res.moveToFirst()){
        do{
            array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_SCORE)));
        }while(res.moveToNext());
    }
    res.close(); // 用完关闭Cursor,避免内存泄漏
    return array_list;
}

如果一定要手动拼接SQL,需要给日期值两侧加单引号,写法为"select score from stats WHERE date = '"+date+"'",但该写法非常不推荐,一旦参数包含单引号会直接触发SQL语法错误。

内容的提问来源于stack exchange,提问作者Aditya Pathak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:06:01