使用 Flutter 插入 sqflite 时出现问题

Posted

技术标签:

【中文标题】使用 Flutter 插入 sqflite 时出现问题【英文标题】:Problem inserting into sqflite using Flutter 【发布时间】:2020-11-10 17:01:39 【问题描述】:

我在 Flutter 中遇到 sqflite 问题。 正常插入工作得很好......但是一旦我插入一个值,即 id 我从将 int 插入第一个表中得到,我在“)”附近得到一个语法错误。

这是我得到的错误:

flutter: 错误 DatabaseException(Error Domain=FMDatabase Code=1 "near ")": 语法错误" UserInfo=NSLocalizedDescription=near ")": 语法 错误) sql 'CREATE TABLE pageM (id INTEGER PRIMARY KEY,caardId INTEGER,title INTEGER,content TEXT,)' args [] 在​​打开、关闭... [VERBOSE-2:ui_dart_state.cc(157)] 未处理的异常: DatabaseException(错误域=FMDatabase 代码=1“近”):语法 error" UserInfo=NSLocalizedDescription=near ")": 语法错误) sql 'CREATE TABLE pageM (id INTEGER PRIMARY KEY,caardId INTEGER,title 整数,内容文本,)' args [] #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) #1 SqfliteDatabaseFactoryImpl.wrapDatabaseException(包:sqflite/src/factory_impl.dart:78:7) #2 SqfliteDatabaseMixin.safeInvokeMethod(包:sqflite_common/src/database_mixin.dart:208:15) #3 SqfliteDatabaseMixin.invokeExecute (package:sqflite_common/src/database_mixin.dart:370:12) #4 SqfliteDatabaseMixin.txn 执行。 (包:sqflite_common/src/database_mixin.dart:362:14) #5 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:312:26) #6 SqfliteDatabaseMixin.txnWriteSynchronized (包:sqflite_common/src/database_mixin.dart:345:

这是我的插入:

onPressed: () async 
    currentCaard = Caard(topicId: widget.topicId, pageAmount: widget.pageAmount);
    print(currentCaard);
    currentCaard.id = await DatabaseProviderCaard.db.insert(currentCaard);
    currentPage = PageM(caardId: currentCaard.id, title: textControllerTitle.text,content: textControllerContent.text);
    DatabaseProviderPage.db.insert(currentPage);
,

这是我的整个 db Provider 文件:

import 'package:caards/model.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';

class DatabaseProviderCaard 
  static const String TABLE_CAARD = "caard";
  static const String COLUMN_ID = "id";
  static const String COLUMN_TOPIC_ID = "topicId";
  static const String COLUMN_PAGE_AMOUNT = "pageAmount";

  DatabaseProviderCaard._();
  static final DatabaseProviderCaard db = DatabaseProviderCaard._();

  Database _database;

  Future<Database> get database async 
    print("caard database getter called");

    if (_database != null) 
      return _database;
    

    _database = await createDatabase();

    return _database;
  

  Future<Database> createDatabase() async 
    String dbPath = await getDatabasesPath();

    return await openDatabase(
        join(dbPath, 'caardDB.db'),
        version: 1,
        onCreate: (Database  database, int version) async 
        print("Creating caard table");

        await database.execute(
          "CREATE TABLE $TABLE_CAARD ("
              "$COLUMN_ID INTEGER PRIMARY KEY,"
              "$COLUMN_TOPIC_ID INTEGER,"
              "$COLUMN_PAGE_AMOUNT INTEGER"
              ")",
          );
        ,
    );
  

  Future<List<Caard>> getCaards() async 
    final db = await database;

    var caards = await db
        .query(TABLE_CAARD, columns: [COLUMN_ID, COLUMN_TOPIC_ID, COLUMN_PAGE_AMOUNT]);

    List<Caard> caardList = List<Caard>();

    caards.forEach((currentCaard) 
      Caard caard = Caard.fromMap(currentCaard);

      caardList.add(caard);
    );

    return caardList;
  

  Future<int> insert(Caard caard) async 
    final db = await database;
    caard.id = await db.insert(TABLE_CAARD, caard.toMap());
    return caard.id;
  

  Future<int> delete(int id) async 
    final db = await database;

    return await db.delete(
      TABLE_CAARD,
      where: "id = ?",
      whereArgs: [id],
    );
  

  Future<int> update(Caard caard) async 
    final db = await database;

    return await db.update(
      TABLE_CAARD,
      caard.toMap(),
      where: "id = ?",
      whereArgs: [caard.id],
    );
  



class DatabaseProviderPage 
  static const String TABLE_PAGE = "page";
  static const String COLUMN_ID = "id";
  static const String COLUMN_CAARD_ID = "caardId";
  static const String COLUMN_TITLE = "title";
  static const String COLUMN_CONTENT = "content";


  DatabaseProviderPage._();
  static final DatabaseProviderPage db = DatabaseProviderPage._();

  Database _database;

  Future<Database> get database async 
    print("page database getter called");

    if (_database != null) 
      return _database;
    

    _database = await createDatabase();

    return _database;
  

  Future<Database> createDatabase() async 
    String dbPath = await getDatabasesPath();

    return await openDatabase(
      join(dbPath, 'pageDB.db'),
      version: 1,
      onCreate: (Database  database, int version) async 
        print("Creating page table");

        await database.execute(
          "CREATE TABLE $TABLE_PAGE ("
              "$COLUMN_ID INTEGER PRIMARY KEY,"
              "$COLUMN_CAARD_ID INTEGER,"
              "$COLUMN_TITLE INTEGER,"
              "$COLUMN_CONTENT TEXT,"
              ")",
        );
      ,
    );
  

  Future<List<PageM>> getPages() async 
    final db = await database;

    var pages = await db
        .query(TABLE_PAGE, columns: [COLUMN_ID, COLUMN_CAARD_ID, COLUMN_TITLE, COLUMN_CONTENT]);

    List<PageM> pageList = List<PageM>();

    pages.forEach((currentPage) 
      PageM page = PageM.fromMap(currentPage);

      pageList.add(page);
    );

    return pageList;
  

  Future<PageM> insert(PageM pageM) async 
    final db = await database;
    pageM.id = await db.insert(TABLE_PAGE, pageM.toMap());
    return pageM;
  

  Future<int> delete(int id) async 
    final db = await database;

    return await db.delete(
      TABLE_PAGE,
      where: "id = ?",
      whereArgs: [id],
    );
  

  Future<int> update(PageM page) async 
    final db = await database;

    return await db.update(
      TABLE_PAGE,
      page.toMap(),
      where: "id = ?",
      whereArgs: [page.id],
    );
  

这是我的模型:

import 'package:caards/database_provider.dart';

class Caard 
  int id;
  int topicId;
  int pageAmount;

  Caard(this.id, this.topicId, this.pageAmount);

  Map<String, dynamic> toMap() 
    var map = <String, dynamic>
      DatabaseProviderCaard.COLUMN_ID: id,            //versuch
      DatabaseProviderCaard.COLUMN_TOPIC_ID: topicId,
      DatabaseProviderCaard.COLUMN_PAGE_AMOUNT: pageAmount
    ;
    
    if (id != null) 
      map[DatabaseProviderCaard.COLUMN_ID] = id;
    
    
    return map;
  
  
  Caard.fromMap(Map<String, dynamic> map) 
    id = map[DatabaseProviderCaard.COLUMN_ID];
    topicId = map[DatabaseProviderCaard.COLUMN_TOPIC_ID];
    pageAmount = map[DatabaseProviderCaard.COLUMN_PAGE_AMOUNT];
  




class PageM 
  int id;
  int caardId;
  String title;
  String content;

  PageM(this.id, this.caardId, this.title, this.content);

  Map<String, dynamic> toMap() 
    var map = <String, dynamic>
      DatabaseProviderPage.COLUMN_CAARD_ID: caardId, 
      DatabaseProviderPage.COLUMN_TITLE: title,
      DatabaseProviderPage.COLUMN_CONTENT: content
    ;

    if (id != null) 
      map[DatabaseProviderPage.COLUMN_ID] = id;
    

    return map;
  

  PageM.fromMap(Map<String, dynamic> map) 
    id = map[DatabaseProviderPage.COLUMN_ID];
    caardId = map[DatabaseProviderPage.COLUMN_CAARD_ID];
    title = map[DatabaseProviderPage.COLUMN_TITLE];
    content = map[DatabaseProviderPage.COLUMN_CONTENT];
  


```

【问题讨论】:

【参考方案1】:

您需要在语法上更正 SQL 查询。 您目前使用:

'CREATE TABLE pageM (id INTEGER PRIMARY KEY,caardId INTEGER,title INTEGER,content TEXT,)'

此查询末尾有一个额外的逗号,这在语法上不正确。这就是数据库抱怨语法错误的原因。事实上,在 DB 的错误消息中,有使用代码创建的查询,其中括号前有一个尾随逗号“,”。更改您的代码,以便查询是:

 'CREATE TABLE pageM (id INTEGER PRIMARY KEY,caardId INTEGER,title INTEGER,content TEXT)'

您需要更改 DB Provider 文件中的以下部分。 错误是因为下面部分TEXT后面有个逗号:

 await database.execute(
          "CREATE TABLE $TABLE_PAGE ("
              "$COLUMN_ID INTEGER PRIMARY KEY,"
              "$COLUMN_CAARD_ID INTEGER,"
              "$COLUMN_TITLE INTEGER,"
              "$COLUMN_CONTENT TEXT,"
              ")",

正确的版本如下。

await database.execute(
          "CREATE TABLE $TABLE_PAGE ("
              "$COLUMN_ID INTEGER PRIMARY KEY,"
              "$COLUMN_CAARD_ID INTEGER,"
              "$COLUMN_TITLE INTEGER,"
              "$COLUMN_CONTENT TEXT"
              ")",

【讨论】:

以上是关于使用 Flutter 插入 sqflite 时出现问题的主要内容,如果未能解决你的问题,请参考以下文章

Flutter 将数据插入数据库 sqflite

如何在SQFlite中插入POJO对象和列表

Flutter Provider 和 sqflite 集成

Flutter中的Sqflite,使用两个数据库(附件)

Flutter:如何使用SQFlite存储的数据?

在 Flutter 中使用 SQFlite 将本地存储的 DB 导出为可读文件