How to create multiple tables in a database in sqflite?

后端 未结 6 1891
礼貌的吻别
礼貌的吻别 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 11:53

    You can use a .sql file that contains your DB script.

    First,add the script file to assets.

    Then, import the following packages:

    import 'package:path/path.dart';
    
    import 'package:sqflite/sqflite.dart';
    
    import 'package:flutter/services.dart' show rootBundle;
    

    finally, use the following code

    void _createDb() async 
    {
          final database = openDatabase( join( await getDatabasesPath(), 'mydb.db'),
          onCreate: (db, version) async  
          {
              // call database script that is saved in a file in assets
              String script =  await rootBundle.loadString("assets\\db\\script.sql");
              List scripts = script.split(";");
              scripts.forEach((v) 
              {
                  if(v.isNotEmpty ) 
                  {
                       print(v.trim());
                       db.execute(v.trim());
                  }
              });
           },
           version: 1,
           );
    }
    

提交回复
热议问题