Flutter 如何更新版本数据库SQFLite flatter?
我需要在本地数据库中创建新表并删除其他表,但是仅更改数据库版本是不起作用的,它不会创建我需要的新表 以同样的方式,我已经尝试过onUpgrade,但它不起作用Flutter 如何更新版本数据库SQFLite flatter?,flutter,sqflite,Flutter,Sqflite,我需要在本地数据库中创建新表并删除其他表,但是仅更改数据库版本是不起作用的,它不会创建我需要的新表 以同样的方式,我已经尝试过onUpgrade,但它不起作用 Future<Database> get database async{ if( _database != null )return _database; _database = await initDB(); return _database; } initDB()async {
Future<Database> get database async{
if( _database != null )return _database;
_database = await initDB();
return _database;
}
initDB()async {
Directory documentDirectory = await getApplicationDocumentsDirectory();
String path = join( documentDirectory.path, 'DB.db' );
var ouDb = await openDatabase(path, version: 2,onCreate: onCreate, onUpgrade: onUpgrade);
return ouDb;
}
FutureOr<void> onCreate(Database db, int version) async {
await db.execute('CREATE TABLE nameTable0...');
db.execute("DROP TABLE IF EXISTS NameTable1");
db.execute("DROP TABLE IF EXISTS NameTable2");
}
FutureOr<void> onUpgrade(Database db, int oldVersion, int newVersion) async{
if (oldVersion < newVersion) {
await db.execute('CREATE TABLE NameTable3 ...');
}
//onCreate(db, newVersion);
}
Future-get-database-async{
如果(_database!=null)返回_database;
_数据库=等待initDB();
返回数据库;
}
initDB()异步{
Directory documentDirectory=等待getApplicationDocumentsDirectory();
String path=join(documentDirectory.path,'DB.DB');
var ouDb=await openDatabase(路径,版本:2,onCreate:onCreate,onUpgrade:onUpgrade);
返回ouDb;
}
FutureOr onCreate(数据库数据库数据库,int版本)异步{
wait db.execute('CREATE TABLE nameTable0…');
db.execute(“如果存在,则删除表NameTable1”);
db.execute(“如果存在,则删除表NameTable2”);
}
FutureOr onUpgrade(数据库数据库数据库、int旧版本、int新版本)异步{
如果(旧版本<新版本){
wait db.execute('CREATE TABLE NameTable3…');
}
//onCreate(db,新版本);
}
您需要使用onUpgrade
initDb()异步{
Directory documentDirectory=等待getApplicationDocumentsDirectory();
String path=join(documentDirectory.path,'maindb.db');
var ourDb=await openDatabase(路径,版本:2,onCreate:_onCreate,onUpgrade:_onUpgrade);
返回我们的数据库;
}
//升级数据库表
void _onUpgrade(数据库数据库、int旧版本、int新版本){
如果(旧版本<新版本){
//您可以执行drop table和create table
execute(“ALTER TABLE tb_name ADD COLUMN newCol TEXT;”);
}
}
我已经试过了,我只是再试了一次,但它没有检测到更改@Sanjay Sharma你说的“它没有检测到更改”是什么意思?我设置了一个断点,它没有超出这一行Directory documentDirectory=wait getApplicationDocumentsDirectory()代码>因为它不再到达onUpgrade所在的行,我不知道为什么在这一行上'if(_database!=null)返回_database;它验证了如果已经有一个bd,它将不再执行initDB,我是一个新的颤振,所以我在一个我正在看的课程中支持了我自己,它只说随着版本号的增加,它会检测到bd@Sanjay SharmaCan中的变化。你发布了你正在使用的修改过的代码吗?试着将版本更改为3并运行它。我想在您编写onUpgrade