Flutter Sqflite sql 'BEGIN EXCLUSIVE' args []} во время открытия, закрытия - PullRequest
0 голосов
/ 05 августа 2020

Я получаю такую ​​ошибку при создании двух таблиц. Кстати, я новичок в sqflite:)

flutter: error DatabaseException (Error Domain = FMDatabase Code = 6922 "disk I / O error" UserInfo = {NSLocalizedDescription = disk I / O error} ) sql 'BEGIN EXCLUSIVE' args []} во время открытия, закрытия ... [VERBOSE-2: ui_dart_state. cc (157)] Необработанное исключение: DatabaseException (Error Domain = FMDatabase Code = 6922 "дисковый ввод-вывод error "UserInfo = {NSLocalizedDescription = ошибка дискового ввода-вывода}) sql аргументы 'BEGIN EXCLUSIVE' []}

Мой класс модели

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

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");
}

1 Ответ

0 голосов
/ 05 августа 2020

Вы можете скопировать и вставить полный код ниже
Вам понадобится double quote для "${model.albumName}"
фрагмента кода

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),
      ),
    );
  }
}
...