![](/img/trans.png)
[英]Flutter, Sqflite - DatabaseException(no such table: Project...)
[英]flutter sqflite DatabaseException no such table
我在这里尝试使用 sqflite 但是当我尝试插入值时我一直收到此错误没有这样的表但我想创建一个表
SqfliteDatabaseException (DatabaseException(no such table: usernotes (code 1 SQLITE_ERROR): , while compiling: INSERT OR REPLACE INTO usernotes (id, title, content) VALUES (?, ?, ?)) sql 'INSERT OR REPLACE INTO usernotes (id, title, content) VALUES (?, ?, ?)' args [2021-03-05 20:44:59.369377, a new note, what should i do]})
这是我的数据库助手 class 和 controller
import 'package:mynotes/models/note_model.dart';
import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as path;
class DBHelper {
static sql.Database _database;
static Future<void> init() async {
if (_database != null) {
return;
}
try {
var databasePath = await sql.getDatabasesPath();
String _path = path.join(databasePath, 'notes.db');
_database = await sql.openDatabase(_path, version: 1, onCreate: onCreate);
} catch (e) {
print(e);
}
}
static Future onCreate(sql.Database db, int version) async {
await db.execute(
'CREATE TABLE usernotes(id TEXT PRIMARY KEY,title TEXT,content TEXT)');
}
static Future insert(String table, NoteModel noteModel) async =>
await _database.insert(table, noteModel.toMap(),
conflictAlgorithm: sql.ConflictAlgorithm.replace);
}
和这里
import 'package:mynotes/helper/db_helper.dart';
import 'package:mynotes/models/note_model.dart';
class NoteController with ChangeNotifier {
List<NoteModel> _notes = [];
List<NoteModel> get notes => _notes;
Future<void> addToNote(String title, String content) async {
try {
await DBHelper.init();
final newNote = NoteModel(
id: DateTime.now().toString(),
title: title,
content: content,
);
_notes.add(newNote);
notifyListeners();
DBHelper.insert(
'usernotes',
NoteModel(
id: newNote.id, title: newNote.title, content: newNote.content));
notifyListeners();
print(notes);
} catch (e) {
print(e);
}
}}
那么这里的问题是什么? 我尝试运行具有相同功能的其他项目,但没有显示此错误
尝试切换
static Future<void> init() async {
if (_database != null) {
return;
}
try {
var databasePath = await sql.getDatabasesPath();
String _path = path.join(databasePath, 'notes.db');
_database = await sql.openDatabase(_path, version: 1, onCreate: onCreate);
} catch (e) {
print(e);
}}
至
static Future<Database> init() async {
if (_database != null) return _database;
try {
var databasePath = await sql.getDatabasesPath();
String _path = path.join(databasePath, 'notes.db');
_database = await sql.openDatabase(_path, version: 1, onCreate: onCreate);
return _database;
} catch (e) {
print(e);
}}
因为你需要在这里返回数据库。 接下来在最后一段中,您需要替换await DBHelper.init();
到db = await DBHelper.init();
最后DBHelper.insert(...
到db.insert(...
我只需要在打开数据库之前添加这一行
Directory path = await getApplicationDocumentsDirectory();
并使用这条路径
每次修改数据库时,都需要卸载应用程序并重新安装(或尝试增加数据库中的模式版本)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.