在Flutter使用中为数据库创建表之前如何检查数据库是否存在sqflite?
例如,如果我要创建数据库doggie_database.db,我如何过早地检查它在表创建中的存在?
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,
);
Run Code Online (Sandbox Code Playgroud)
您可以使用databaseExists(String path).
https://github.com/tekartik/sqflite/blob/master/sqflite/lib/sqflite.dart(第 174 行)
/// Check if a database exists at a given path.
///
Future<bool> databaseExists(String path) =>
databaseFactory.databaseExists(path);
Run Code Online (Sandbox Code Playgroud)
但我认为您对CREATE TABLE再次调用该声明感到担忧。如果您指定version. 在内部,版本被保留,onCreate如果已经指定则不会被调用。
来自同一个文件:
/// 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2650 次 |
| 最近记录: |