dart - 如何将新表添加到sqlite?

标签 dart flutter sqflite

我需要为现有表的当前数据库添加新的列名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;
  }

如何使用_onUpgrade
void _onUpgrade(Database db, int oldVersion, int newVersion)async{

  }

是否还需要添加列?
void _onCreate(Database db, int version) async {

    await db.execute(
        """CREATE TABLE AssetAssemblyTable(e INTEGER, a INTEGER, c INTEGER)""");

最佳答案

要从旧版本更新数据库,应将version更改为2
您应该像下面那样更改onCreateonUpdate

// 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
  }
}

下面是更多示例

https://github.com/tekartik/sqflite/blob/master/sqflite/doc/migration_example.md

关于dart - 如何将新表添加到sqlite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56248737/

相关文章:

intellij-idea - Alt+Enter 停止在 IntelliJ 中处理 Dart 文件

sqlite - 使用flutter的sqflite报错database_closed

flutter - Flutter中如何使用Column在屏幕中间显示文本?

authorization - 使用 Dart 的 Google Plus API - 状态 401,授权问题

DART:如何编写返回 Future 的耗时函数

flutter - CupertinoDatePicker 禁用当前时间之前的小时和分钟

flutter - 在 Flutter StatefulWidget 中给 initState 内部的变量赋值与不给变量赋值有什么区别吗?

flutter - 在ListView.builder() flutter中动态创建单选按钮Group

sqlite - 使用Sqlite Flutter BETWEEN查询返回最近2天的记录

json - 如何使用 SQFLite 或 Moor 库将 JSON 数据存储到 flutter 中的数据库表中