我需要id INTEGER AUTOINCREMENT为现有表添加当前数据库的新列名和新表。如何使用“onUpgrade”?是否需要更改版本号?
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "HelperDatabase.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate, onUpgrade: _onUpgrade);
return theDb;
}
Run Code Online (Sandbox Code Playgroud)
如何使用_onUpgrade
void _onUpgrade(Database db, int oldVersion, int newVersion)async{
}
Run Code Online (Sandbox Code Playgroud)
还需要加栏吗?
void _onCreate(Database db, int version) async {
await db.execute(
"""CREATE TABLE AssetAssemblyTable(e INTEGER, a INTEGER, c INTEGER)""");
Run Code Online (Sandbox Code Playgroud)
要从旧版本更新数据库,您应该更改version为2. 你应该改变onCreate并onUpdate像下面这样。
// This is called for new users who have no old db
void _onCreate(Database db, int version) async {
// if `AssetAssemblyTable` has a new column in version 2, add the column here.
await db.execute(
"""CREATE TABLE AssetAssemblyTable(e INTEGER, a INTEGER, c INTEGER)""");
)
await db.execute("CREATE TABLE NewTable...") // create new Table
}
// This is called for existing users who have old db(version 1)
void _onUpgrade(Database db, int oldVersion, int newVersion)async{
// In this case, oldVersion is 1, newVersion is 2
if (oldVersion == 1) {
await db.execute("ALTER TABLE AssetAssemblyTable...") // add new column to existing table.
await db.execute("CREATE TABLE NewTable...") // create new Table
}
}
Run Code Online (Sandbox Code Playgroud)
更多示例如下
https://github.com/tekartik/sqflite/blob/master/sqflite/doc/migration_example.md
| 归档时间: |
|
| 查看次数: |
3582 次 |
| 最近记录: |