Search code examples
fluttersqflite

Check if table exists in flutter


I have implemented code to check if database exists in Database Helper class. This is my DatabaseHelper class.

static final DatabaseHelper _instance = new DatabaseHelper.internal();
  DatabaseHelper.internal();
  factory DatabaseHelper() => _instance;

  static Database _db;

  static final table = 'User';

  Future checkDb() async{
     Directory documentDirectory = await getApplicationDocumentsDirectory();
      //var db = await getDatabasesPath();
      var dbPath = join(documentDirectory.path,"main.db");
      bool exist = await databaseExists(dbPath);
      return exist;
  }

  

  Future<Database> get db async{
    if(_db!= null)
    {
      return _db;
    }
    _db = await initdb();
    return _db;
  }

  initdb() async{
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path,"main.db");
    var ourDb = await openDatabase(path,version:1,onCreate:_onCreate);
    return ourDb;

  }

  void _onCreate(Database db,int version)async {
    await db.execute("CREATE TABLE User("
          "userId INTEGER PRIMARY KEY,"
          "first_name TEXT,"
          "last_name TEXT,"
          "user_password TEXT,"
          
          ")");
    print("User Table created");
  }



  void tableIsEmpty()async{
     var db = await openDatabase('main.db');
     
      int count = Sqflite
         .firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM User'));
      
     print(count);
    
  }
  

The Database gets created successfully and db.checkdb() returns true when i call

var db = new DatabaseHelper();

But when i call db.tableIsEmpty() i get an error "no such table:User" even after OnCreate is being executed?

How can i solve the problem or how can i check if table exists in db?


Solution

  • Because openDatabase need full path
    And in your code you have defined

    Future<Database> get db 
    

    So please change from

    var db = await openDatabase('main.db');
    

    to

    var db = await db;
    

    code snippet

    void tableIsEmpty()async{
        var db = await db;
         
        int count = Sqflite
             .firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM User'));
          
         print(count);    
    }