Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a database exists before creating a table?

How do you check whether a database exists before creating a table for the database in Flutter using sqflite?

E.g., if I'm to create the database doggie_database.db, how do I prematurely check its existence within table creation?

final Future<Database> database = openDatabase(
  // Set the path to the database. 
  join(await getDatabasesPath(), 'doggie_database.db'),
  // When the database is first created, create a table to store dogs.
  onCreate: (db, version) {
    // Run the CREATE TABLE statement on the database.
    return db.execute(
      "CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
    );
  },
  // Set the version. This executes the onCreate function and provides a
  // path to perform database upgrades and downgrades.
  version: 1,
);
like image 302
evergreen Avatar asked Jul 28 '19 10:07

evergreen


People also ask

How can I tell if a SQL Server database is being used?

Another way to see if your database is in use is to look and see if the indexes are being used. Information on index usage is held in the sys. dm_db_index_usage_stats table since the last server reboot, and can be queried using this statement which can be tailored to select the data you need.

How do you know if a table is present in a database?

To check if table exists in a database you need to use a Select statement on the information schema TABLES or you can use the metadata function OBJECT_ID(). The INFORMATION_SCHEMA. TABLES returns one row for each table in the current database.

How do you check if a table already exists in SQL?

Using the OBJECT_ID and the IF ELSE statement to check whether a table exists or not. Alternative 2 : Using the INFORMATION_SCHEMA. TABLES and SQL EXISTS Operator to check whether a table exists or not.


1 Answers

You can check if a database exists with databaseExists(String path).

https://github.com/tekartik/sqflite/blob/master/sqflite/lib/sqflite.dart (line 174)

/// Check if a database exists at a given path.
///
Future<bool> databaseExists(String path) =>
    databaseFactory.databaseExists(path);

But I think you are concerned with the CREATE TABLE statement being called again. You should not worry about this if you specify the version. Internally the version is kept and onCreate isn't called if it's already specified.

From the same file:

/// If [version] is specified, [onCreate], [onUpgrade], and [onDowngrade] can
/// be called. These functions are mutually exclusive — only one of them can be
/// called depending on the context, although they can all be specified to
/// cover multiple scenarios
///
/// [onCreate] is called if the database did not exist prior to calling
/// [openDatabase]. You can use the opportunity to create the required tables
/// in the database according to your schema
like image 155
dumazy Avatar answered Sep 16 '22 16:09

dumazy