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

Flutter Sqflite数据库新增条目报错问题技术求助

Flutter Sqflite 添加数据报错解决办法

我开发了一个基于Flutter框架的应用,使用Sqflite作为数据库,但在尝试创建/添加新条目时出现报错。以下是用于创建新条目的代码:

static Future<int> createItem(String title, String descrption, String start, String end, String location) async {
  final db = await SQLHelper.db();

  final data = {
    'title': title,
    'description': descrption,
    'start time': start,
    'end time': end,
    'location': location,
    'createdAt': DateTime.now().toString()
  };
  final id = await db.insert('items', data,conflictAlgorithm: sql.ConflictAlgorithm.replace);
  return id;
}

问题原因

报错的核心原因是数据键名start time和end time包含空格,Sqflite底层依赖SQLite,而SQLite中未转义的带空格列名会被解析为多个SQL关键字,直接触发语法错误。

解决方法

方法1:统一使用无空格列名(推荐)

修改数据库表的列名,用下划线替代空格,同时同步修改插入代码的键名,这是最规范的做法,能避免后续其他SQL操作的潜在问题。

修改后的插入代码:

static Future<int> createItem(String title, String descrption, String start, String end, String location) async {
  final db = await SQLHelper.db();

  final data = {
    'title': title,
    'description': descrption,
    'start_time': start,
    'end_time': end,
    'location': location,
    'createdAt': DateTime.now().toString()
  };
  final id = await db.insert('items', data,conflictAlgorithm: sql.ConflictAlgorithm.replace);
  return id;
}

同时要保证创建items表的SQL语句中列名对应修改:

CREATE TABLE IF NOT EXISTS items (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT,
  description TEXT,
  start_time TEXT,
  end_time TEXT,
  location TEXT,
  createdAt TEXT
);

方法2:保留空格列名,手动编写转义后的SQL语句

如果必须保留带空格的列名,需要在插入时用反引号包裹列名,通过rawInsert执行手动编写的SQL:

static Future<int> createItem(String title, String descrption, String start, String end, String location) async {
  final db = await SQLHelper.db();

  final insertSql = '''
    INSERT INTO items (title, description, `start time`, `end time`, location, createdAt)
    VALUES (?, ?, ?, ?, ?, ?)
  ''';
  final id = await db.rawInsert(
    insertSql,
    [title, descrption, start, end, location, DateTime.now().toString()],
  );
  return id;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:45:37