How to create multiple tables in a database in sqflite?

后端 未结 6 1946
礼貌的吻别
礼貌的吻别 2021-01-11 11:51

Im building and app with flutter that uses SQLite database. I have created first table using this piece of code:

 void _createDb(Database db, int newVersion)         


        
6条回答
  •  长情又很酷
    2021-01-11 12:10

    in openDatabase(path, onCreate, version) use one more optional parameter "onUpgrade" and define the dropping and again creating table scripts. and also upgrade(increase) the parameter version by one.

    ----- Code snippet ------

    openDatabase(path, onCreate:_createDb, onUpgrade: onUpgrade,version:_DB_VERSION);
    ...
    ...
    
        _onUpgrade( Database db, int oldVersion, int newVersion ) async {
    
        Batch batch = db.batch();
    
        // drop first
    
        batch.execute("DROP TABLE IF EXISTS $_TABLE_3 ;");
    
        batch.execute("DROP TABLE IF EXISTS $_TABLE_2 ;");
        batch.execute("DROP TABLE IF EXISTS $_TABLE_1 ;");
        // then create again
        batch.execute("CREATE TABLE $TABLE_1 ...... ");
        batch.execute("CREATE TABLE $TABLE_2 ...... ");
        batch.execute("CREATE TABLE $TABLE_3 ...... ");
        List result = await batch.commit();
    
    }
    

    Note: Each and every time when you will create or change the structure of some table(s), you will have to increase database version in openDatabase() method. so that the upgradation will be called, otherwise it will not be called.

提交回复
热议问题