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

如何在sqflite中使用LIKE语句及%/*通配符查询数据库?

Ah, I see the issue here! The problem with your current query is that you're trying to wrap the placeholder ? directly with % in the SQL string, which sqflite (and SQLite in general) doesn't accept as valid syntax. Let me break down how to fix this properly.

The safest and cleanest way is to add the wildcard characters to your filter criteria before passing it as a parameter. This also helps prevent SQL injection risks.

Modify your query line like this:

var res = await db.rawQuery("SELECT * FROM Companies WHERE name LIKE ?;", ['%$filterCriteria%']);

Method 2: Use SQLite's string concatenation operator ||

If you prefer to handle the wildcards directly in the SQL statement, you can use SQLite's || operator to concatenate the % with your placeholder:

var res = await db.rawQuery("SELECT * FROM Companies WHERE name LIKE '%' || ? || '%';", [filterCriteria]);

Also, fix the model conversion bug!

I noticed a typo in your code: you're trying to add a JobModel to a list of CompanyModel. Make sure to use CompanyModel.fromDb(item) instead to avoid type errors:

filteredCompanies.add(CompanyModel.fromDb(item));

Full corrected code example

Here's the updated function with the recommended method (plus a minor improvement to check for non-empty results):

Future<List<CompanyModel>> filterCompanies(String filterCriteria) async {
  final db = await database;
  List<CompanyModel> filteredCompanies = [];
  var res = await db.rawQuery(
    "SELECT * FROM Companies WHERE name LIKE ?;",
    ['%$filterCriteria%']
  );
  if (res.isNotEmpty) {
    for (var item in res) {
      filteredCompanies.add(CompanyModel.fromDb(item));
    }
  }
  return filteredCompanies;
}

Why your original code failed

SQLite expects the placeholder ? to be a standalone token in the query string. Writing %?% confuses the parser because it doesn't recognize ? as a valid placeholder when it's wrapped between % characters. By either attaching the % to the parameter value or concatenating them in SQL, you're giving SQLite a valid expression to evaluate.

内容的提问来源于stack exchange,提问作者Diligence Vagere

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:26:16