sqlite 使用颤动的SQFlite时出现错误DATABASE_CLOSED

3pmvbmvn  于 2022-11-15  发布在  SQLite
关注(0)|答案(3)|浏览(325)

我尝试使用SQFlite保存一些数据,如我的类Movie,但当我尝试在数据库上插入或查询时,会看到以下消息:

[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: DatabaseException(error database_closed)

我的MovieBloc类:

List<Movie> _movies = new List<Movie> ();
class MoviesBloc implements BaseBloc {
  final  _moviesController = StreamController<List<Movie>>();
  Database moviesDB;
  String _moviesPath;
  Stream<List<Movie>> get moviesStream => _moviesController.stream;
  List<Movie> get movies => _movies;

  int getLengthMovieList() {
    return _movies.length;
  }
  clearMovieList() {
    _movies.clear();
  }

  Future<void> openMovieDB({String dbName:'movies.db'}) async {

    var databasesPath = await getDatabasesPath();
    _moviesPath = join(databasesPath, dbName);

    moviesDB = await openDatabase(_moviesPath, version: 1,
        onCreate: (Database db, int version) async {
          await db.execute(
              'CREATE TABLE movies (Id INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT NOT NULL, imdbRating TEXT, Poster TEXT, Plot TEXT, Saved INTEGER DEFAULT 0)');
        });
  }
  Future<void> closeMovieDB() async => moviesDB.close();

  void dispose() {
    _moviesController.close();
  }
}

我的MovieProvider类:

class MovieProvider extends MoviesBloc {
  String _tableName = 'movies';

  Future<Movie> insert(Movie movie, {conflictAlgorithm: ConflictAlgorithm.ignore}) async {
    await moviesDB.insert(_tableName, movie.toMap(), conflictAlgorithm: conflictAlgorithm);
    return movie;
  }

  Future<bool> insertAll(List<Movie> movies) async {
    await Future.wait(movies.map((movie) async {
      await this.insert(movie);
    }
    ));
    return true;
  }

  Future<List<Movie>> paginate(int page, {int limit: 15}) async {
    print('in Paginate to SQLite');
    List<Map> maps  = await moviesDB.query(_tableName,
        columns: ['Id', 'Title', 'imdbRating', 'Poster', 'Plot', 'Saved'],
        limit: limit,
        offset: page == 1 ? 0 : ((page -1) * limit)
    );
    List<Movie> movies = new List<Movie> ();
      if (maps.length > 0) {
        maps.map((movie) {
          movies.add(Movie.fromJson(movie));
        }
        );
      }
    return movies;
  }
}

我对SQFlite使用的save方法:

static Future<bool> saveAllMoviesIntoSqlite(List<Movie> movies) async {
    var db = new MovieProvider();
    await db.openMovieDB();
    await db.insertAll(movies);
    await db.closeMovieDB();
    return true;
  }

我的来自SQFlite的load方法:

static Future<Map> getAllMoviesFromSqlite(int page) async {
    var db = new MovieProvider();
    await db.openMovieDB();
    List<Movie> movies = new List<Movie> ();
    movies = await db.paginate(page);
    await db.closeMovieDB();
    return {
      "currentPage": page,
      "movies": movies
    };
  }
  • 我观察到insertAll方法来自MovieProvider类,用于将movies列表中的任何电影插入到带有等待和异步的SQ:
Future<bool> insertAll(List<Movie> movies) async {
    await Future.wait(movies.map((movie) async {
      await this.insert(movie);
    }
    ));
    return true;
  }
  • 我尝试closeopen数据库有时顺序和其他玩法与closeopen数据库...

我的日志:

I/flutter ( 1617): in Paginate to SQLite
E/flutter ( 1617): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: DatabaseException(error database_closed)
E/flutter ( 1617): #0      SqfliteDatabaseMixin.checkNotClosed (package:sqflite_common/src/database_mixin.dart:282:7)
E/flutter ( 1617): #1      SqfliteDatabaseExecutorMixin._rawQuery (package:sqflite_common/src/database_mixin.dart:125:8)
E/flutter ( 1617): #2      SqfliteDatabaseExecutorMixin.query (package:sqflite_common/src/database_mixin.dart:110:12)
E/flutter ( 1617): #3      MovieProvider.paginate (package:umdb/bloc/movie_provider.dart:24:38)
E/flutter ( 1617): #4      MovieService.getAllMoviesFromSqlite (package:umdb/services/movie_service.dart:54:23)
E/flutter ( 1617): <asynchronous suspension>
E/flutter ( 1617): #5      MovieService.getSavedFromSQ (package:umdb/services/movie_service.dart:95:26)
E/flutter ( 1617): #6      MovieService.fetchSavedMovies (package:umdb/services/movie_service.dart:105:5)
E/flutter ( 1617): <asynchronous suspension>
E/flutter ( 1617): #7      MovieDetailState.build.<anonymous closure>.<anonymous closure> (package:umdb/ui_widgets/movie_detail.dart:168:42)
E/flutter ( 1617): #8      State.setState (package:flutter/src/widgets/framework.dart:1240:30)
E/flutter ( 1617): #9      MovieDetailState.build.<anonymous closure> (package:umdb/ui_widgets/movie_detail.dart:142:27)
E/flutter ( 1617): #10     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter ( 1617): #11     TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter ( 1617): #12     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter ( 1617): #13     BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:256:7)
E/flutter ( 1617): #14     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:158:27)
E/flutter ( 1617): #15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:224:20)
E/flutter ( 1617): #16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter ( 1617): #17     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter ( 1617): #18     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter ( 1617): #19     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter ( 1617): #20     _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 1617): #21     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 1617): #22     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 1617): #23     _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter ( 1617): #24     _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)

请帮我修一下

iyfamqjs

iyfamqjs1#

打开/关闭数据库是非常困难的。确实有很多情况下,您可能会访问关闭的数据库,更糟糕的是,如果您打开两次相同的数据库,您将获得相同的示例,因此第一次关闭将关闭数据库。
就我个人而言,我建议让数据库保持开放。
如果您需要处理多个数据库并在短时间内打开/关闭它们,请确保您拥有适当的互斥/锁定机制,以便您可以控制数据库的打开/访问/关闭方式,而不会有任何其他方法试图同时访问相同的数据库(OK,这部分不是明确的,抱歉)。
类似的东西(尽管我真的不建议每次都打开/关闭):

import 'package:synchronized/synchronized.dart';

final static _lock = Lock();

static Future<bool> saveAllMoviesIntoSqlite(List<Movie> movies) async {
  return _lock.synchronized(() {
    var db = new MovieProvider();
    await db.openMovieDB();
    await db.insertAll(movies);
    await db.closeMovieDB();
    return true;
  });
}

static Future<Map> getAllMoviesFromSqlite(int page) async {
  return _lock.synchronized(() {
    var db = new MovieProvider();
    await db.openMovieDB();
    List<Movie> movies = new List<Movie> ();
    movies = await db.paginate(page);
    await db.closeMovieDB();
    return {
      "currentPage": page,
      "movies": movies
    };
  });
}
2ledvvac

2ledvvac2#

关闭数据库时,需要将数据库示例设置为空。否则,它将始终返回旧示例。

Future close() async {
    final db = await instance.database;
    _database = null;
    return db.close();
}
5cg8jx4n

5cg8jx4n3#

保持数据库不关闭,使用Singleton pattern是解决这个问题的一个很好的选择。
1-创建新文件sql_lite_service.dart,该文件将包含具有以下完整代码的SqlLiteService类:

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class SqlLiteService {
  String dBName = 'my_db_name';
  int dBVersion = 1;

  // Singleton pattern
  static final SqlLiteService _databaseService = SqlLiteService._internal();
  factory SqlLiteService() => _databaseService;
  SqlLiteService._internal();
  static Database? _database;

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    // Set the version. This executes the onCreate function and provides a
    // path to perform database upgrades and downgrades.
    Database db = await _getDB();

    return db;
  }

  Future<Database> _getDB() async{
    final path = await _getPath(); // Get a location using getDatabasesPath

    return await openDatabase(
      path,
      onCreate: _onCreate,
      version: dBVersion,
      onConfigure: (db) async => await db.execute('PRAGMA foreign_keys = ON'),
    );
  }

  // create tables
  Future<void> _onCreate(Database db, int version) async {
    // Run the CREATE {users} TABLE statement on the database.
    await db.execute(
        'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, created_at datetime default current_timestamp, updated_at datetime default current_timestamp)'
    );
    // todo: Add your code here ...
  }

  Future<String> _getPath() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, dBName);
    return path;
  }

}

2-现在您可以通过以下方式从任何其他类获取数据库示例:

final Database database = await SqlLiteService().database;
          
// usage example
await database.rawDelete(
  'DELETE FROM users WHERE id = ?',
  [1]
);

使用此方法将解决database_closed错误...

相关问题