【问题标题】:How to add new table to sqlite?如何向sqlite添加新表?
【发布时间】:2019-05-22 03:03:02
【问题描述】:

我需要为我现有的表添加一个新的列名id INTEGER AUTOINCREMENT 和一个用于当前数据库的新表。如何使用“升级”?是否需要更改版本号?

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)""");

【问题讨论】:

    标签: dart flutter sqflite


    【解决方案1】:

    要从旧版本更新您的数据库,您应该将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

    【讨论】:

    • Alter table是否需要增加_onCreate()方法版本号?
    • 您不必对_onCreate 中的version 变量做任何事情。我猜这是为了调试目的。
    • 错误信息:Unhandled Exception: DatabaseException(table UsernameTable has no column named rememberMe (Sqlite code 1): , while compiling: INSERT OR REPLACE INTO UsernameTable (username, rememberMe) VALUES (?, ?), (OS error - 2:No such file or directory)) sql 'INSERT OR REPLACE INTO UsernameTable (username, rememberMe) VALUES (?, ?)' args [term@melfs, 1]}
    • initDb() async { io.Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, "HelperDatabase.db"); var theDb = await openDatabase(path, version: 4, onCreate: _onCreate, onUpgrade: _onUpgrade); return theDb; }
    • void _onUpgrade(Database db, int oldVersion, int newVersion)async{ if(oldVersion != 5){ await db.execute("ALTER TABLE UsernameTable ADD COLUMN rememberMe INTEGER DEFAULT 0"); } }
    猜你喜欢
    • 2021-09-23
    • 1970-01-01
    • 2010-12-25
    • 2021-07-20
    • 2021-10-07
    • 2015-08-22
    • 2021-07-04
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多