Flutter Sqflite sql 'BEGIN EXCLUSIVE' args []} 在​​打开、关闭期间

Flutter Sqflite sql 'BEGIN EXCLUSIVE' args []} during open, closing

当我创建两个表时出现这样的错误。顺便说一句,我是 sqflite 的菜鸟 :)

flutter: error DatabaseException(Error Domain=FMDatabase Code=6922 "disk I/O error" UserInfo={NSLocalizedDescription=disk I/O error}) sql 'BEGIN EXCLUSIVE' args []} during open, closing... [VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: DatabaseException(Error Domain=FMDatabase Code=6922 "disk I/O error" UserInfo={NSLocalizedDescription=disk I/O error}) sql 'BEGIN EXCLUSIVE' args []}

我的模型Class

AlbumModel clientFromJson(String str) {
final jsonData = json.decode(str);
return AlbumModel.fromMapAlbum(jsonData);
}

String clientToJson(AlbumModel data) {
final dyn = data.toMapAlbum();
return json.encode(dyn);
}

class AlbumModel {
 int albumId;
 String albumName;
 int photoId;
 String photoName;
 String dateTime;

 AlbumModel({this.albumId, this.albumName});

 AlbumModel.photo({this.photoId, this.albumId, this.dateTime, this.photoName});

 factory AlbumModel.fromMapAlbum(Map<String, dynamic> json) => AlbumModel(albumId: json["albumId"], albumName: json["albumName"]);

 factory AlbumModel.fromMapPhoto(Map<String, dynamic> json) =>
 AlbumModel.photo(photoId: json["photoId"], albumId: json["albumId"], dateTime: json["dateTime"], photoName: json["photoName"]);

Map<String, dynamic> toMapAlbum() => {
    "albumId": albumId,
    "albumName": albumName,
  };

Map<String, dynamic> toMapPhoto() => {
    "photoId": photoId,
    "albumId": albumId,
    "dateTime": dateTime,
    "photoName": photoName,
  };
}

我的 DBProvider class

DBProvider._();

static final DBProvider db = DBProvider._();

static Database _database;

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

initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String dir = documentsDirectory.path + "/ApplicationFolder";
String path = join(dir, "myDatabase.db");
return await openDatabase(path, version: 1, onOpen: (db) {}, onCreate: (Database db, int version) async {
  await db.execute('CREATE TABLE Album (albumId INTEGER PRIMARY KEY, albumName TEXT)');
  await db.execute('CREATE TABLE Photo (photoId INTEGER PRIMARY KEY, photoName TEXT, dateTime TEXT, photoAlbumId INTEGER)');
});
}

newAlbum(AlbumModel model) async {
final db = await database;
var res = await db.rawInsert('Insert into Album (albumId, albumName) Values (${model.albumId},${model.albumName})');
return res;
}

newPhoto(AlbumModel model) async {
final db = await database;
var res = await db.rawInsert(
    'Insert into Photo (photoId, photoName, dateTime, photoAlbumId) Values (${model.photoId},${model.photoName}, ${model.dateTime}, ${model.albumId})');
return res;
}

这是我插入数据库的相册

_saveAlbumName(AlbumModel(albumName: "Album Name", albumId: 0));

_saveAlbumName 方法是

_saveAlbumName(AlbumModel albumModel){
DBProvider.db.newAlbum(albumModel);
debugPrint(albumModel.toString() + " Added");
}

您可以复制粘贴 运行 下面的完整代码
"${model.albumName}"
你需要 double quote 代码片段

var res = await db.rawInsert(
    'Insert into Album (albumId, albumName) Values (${model.albumId},"${model.albumName}")');

完整代码

import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

AlbumModel clientFromJson(String str) {
  final jsonData = json.decode(str);
  return AlbumModel.fromMapAlbum(jsonData);
}

String clientToJson(AlbumModel data) {
  final dyn = data.toMapAlbum();
  return json.encode(dyn);
}

class AlbumModel {
  int albumId;
  String albumName;
  int photoId;
  String photoName;
  String dateTime;

  AlbumModel({this.albumId, this.albumName});

  AlbumModel.photo({this.photoId, this.albumId, this.dateTime, this.photoName});

  factory AlbumModel.fromMapAlbum(Map<String, dynamic> json) =>
      AlbumModel(albumId: json["albumId"], albumName: json["albumName"]);

  factory AlbumModel.fromMapPhoto(Map<String, dynamic> json) =>
      AlbumModel.photo(
          photoId: json["photoId"],
          albumId: json["albumId"],
          dateTime: json["dateTime"],
          photoName: json["photoName"]);

  Map<String, dynamic> toMapAlbum() => {
        "albumId": albumId,
        "albumName": albumName,
      };

  Map<String, dynamic> toMapPhoto() => {
        "photoId": photoId,
        "albumId": albumId,
        "dateTime": dateTime,
        "photoName": photoName,
      };
}

class DBProvider {
  DBProvider._();

  static final DBProvider db = DBProvider._();

  static Database _database;

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

  initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String dir = documentsDirectory.path + "/ApplicationFolder";
    String path = join(dir, "myDatabase.db");
    return await openDatabase(path, version: 1, onOpen: (db) {},
        onCreate: (Database db, int version) async {
      await db.execute(
          'CREATE TABLE Album (albumId INTEGER PRIMARY KEY, albumName TEXT)');
      await db.execute(
          'CREATE TABLE Photo (photoId INTEGER PRIMARY KEY, photoName TEXT, dateTime TEXT, photoAlbumId INTEGER)');
    });
  }

  newAlbum(AlbumModel model) async {
    final db = await database;
    var res = await db.rawInsert(
        'Insert into Album (albumId, albumName) Values (${model.albumId},"${model.albumName}")');
    return res;
  }

  newPhoto(AlbumModel model) async {
    final db = await database;
    var res = await db.rawInsert(
        'Insert into Photo (photoId, photoName, dateTime, photoAlbumId) Values (${model.photoId},${model.photoName}, ${model.dateTime}, ${model.albumId})');
    return res;
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  _saveAlbumName(AlbumModel albumModel){
    DBProvider.db.newAlbum(albumModel);
    debugPrint(albumModel.toString() + " Added");
  }

  void _incrementCounter() {
    _saveAlbumName(AlbumModel(albumName: "Album Name", albumId: 0));
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}