How to create multiple tables in a database in sqflite?

后端 未结 6 1889
礼貌的吻别
礼貌的吻别 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<String> scripts = script.split(";");
              scripts.forEach((v) 
              {
                  if(v.isNotEmpty ) 
                  {
                       print(v.trim());
                       db.execute(v.trim());
                  }
              });
           },
           version: 1,
           );
    }
    
    0 讨论(0)
  • 2021-01-11 11:55

    yes you can do it

     void _createDb(Database db, int newVersion) async {
     await db.execute('''
       create table $carTable (
        $columnCarId integer primary key autoincrement,
        $columnCarTitle text not null
       )''');
     await db.execute('''
       create table $userTable(
        $userId integer primary key autoincrement,
        $name text not null
       )''');
      }
    

    but to speed up the process, let's assume we have 10 tables, you could use the batch this way

    void _createDb(Database db, int newVersion) async {
    Batch batch = db.batch();
    batch.execute("Your query-> Create table if not exists");
    batch.execute("Your query->Create table if not exists");
    List<dynamic> res = await batch.commit();
    //Insert your controls
    }
    
    0 讨论(0)
  • 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<dynamic> 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.

    0 讨论(0)
  • 2021-01-11 12:12

    You can just combine multiple db.execute calls for exampple

    await db.execute('''
          create table $reminderTable (
            $columnReminderId integer primary key autoincrement,
            $columnReminderCarId integer not null,
            $columnReminderName text not null,
            $columnReminderNotifyMileage integer not null,
            $columnReminderEndMileage integer not null
           )''');
    await db.execute('''
           create table $carTable (
            $columnCarId integer primary key autoincrement,
            $columnCarTitle text not null
           )''');

    0 讨论(0)
  • 2021-01-11 12:16

    Hard to say without seeing your openDatabase call and whether the database exists before or not. One of my guess is that you are still using the same database version. Once onCreate has been called it will never be called again. You should try to bump your database version and add the new table in on onUpgrade

    0 讨论(0)
  • 2021-01-11 12:20

    Change the name of the DB file. This will 'reset' your DB and creation will work.

    e.g:

    final dabasesPath = await getDatabasesPath(); 
    final path = join(dabasesPath, "newName2.db");
    
    0 讨论(0)
提交回复
热议问题