我已经在对象列表中加载了 json 数据。每当我尝试将数据插入表中时,我的控制台都会说“未处理的异常:DatabaseException(没有这样的表:相册(代码 1 SQLITE_ERROR):,编译时:插入或替换到相册......”。我在插入数据之前知道我必须创建数据库和表。我已经在我的代码中完成了。但是由于某种未知的原因,该表没有被构建。这是我的数据库助手类 -
class DatabaseHelper {
static final _dbName = "myDatabase.db";
static final _dbVersion = 1;
static final _tableAlbum = "Album";
static final columnAlbum = '_fetched_album';
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database;
Future<Database?> get database async {
if (_database == null) {
print("instance.db null");
_database ??= await _initiateDatabase();
return _database;
}else{
print("instance.db not null");
return _database; }
}
Future<Database> _initiateDatabase() async {
String directory = await getDatabasesPath();
String path = join(directory, _dbName);
return await openDatabase(
path,
version: _dbVersion,
onCreate:(Database db,int version) async {
await db.execute('''
CREATE TABLE $_tableAlbum (
$columnAlbum TEXT
)''');
},
);
}
Future<int?> insertAlbum(ModelAlbum list) async {
Database? db = await instance.database;
return await db?.insert(
_tableAlbum,list.toMap(),conflictAlgorithm: ConflictAlgorithm.replace);
}
Future<int?> insertPhoto(ModelPhoto list) async {
Database? db = await instance.database;
return await db?.insert(
_tablePhoto,list.toMap(),conflictAlgorithm: ConflictAlgorithm.replace);
}
Future<List<Map<String, dynamic>>> queryAlbum() async {
Database? db = await instance.database;
return await db!.query(_tableAlbum);
}
Future<List<Map<String, dynamic>>> queryPhoto() async {
Database? db = await instance.database;
return await db!.query(_tableAlbum);
}
Future<List<ModelAlbum>> retrieveAlbum() async {
final Database? db = await database;
final List<Map> maps = await db!.query(_tableAlbum);
return List.generate(maps.length, (i) {
return ModelAlbum(
id: maps[i]['id'],
title: maps[i]['title'],
userId: maps[i]['userId'],
);
});
}
Future<List<ModelPhoto>> retrievePhoto() async {
final Database? db = await database;
final List<Map> maps = await db!.query(_tablePhoto);
return List.generate(maps.length, (i) {
return ModelPhoto(
albumId: maps[i]['albumId'],
thumbnailUrl: maps[i]['thumbnailUrl'],
url: maps[i]['url'],
id: maps[i]['id'],
title: maps[i]['title'],
);
});
}
}
每当 Database.instance.insert(object);被称为数据库和表应该自动创建。但它没有。
答案 0 :(得分:1)
您指的是实例方法中的 static
字段。这可能是一个问题尝试从字段中删除静态关键字,
final _dbName = "myDatabase.db";
final _dbVersion = 1;
final _tableAlbum = "Album";
final columnAlbum = '_fetched_album';