-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprovider.dart
73 lines (62 loc) · 1.93 KB
/
provider.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'sql_table_data.dart';
class Provider {
static Database db;
// 获取数据库中所有的表
Future<List> getTables() async {
if (db == null) {
return Future.value([]);
}
List tables = await db
.rawQuery('SELECT name FROM sqlite_master WHERE type = "table"');
List<String> targetList = [];
tables.forEach((item) {
targetList.add(item['name']);
});
return targetList;
}
// 检查数据库中, 表是否完整, 在部份android中, 会出现表丢失的情况
Future checkTableIsRight() async {
List<String> expectTables = ['user']; //将项目中使用的表的表名添加集合中
List<String> tables = await getTables();
for (int i = 0; i < expectTables.length; i++) {
if (!tables.contains(expectTables[i])) {
return false;
}
}
return true;
}
//初始化数据库
Future init() async {
//Get a location using getDatabasesPath
String databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'xxxx.db');
print(path);
try {
db = await openDatabase(path);
} catch (e) {
print("Error $e");
}
bool tableIsRight = await this.checkTableIsRight();
if (!tableIsRight) {
// 关闭上面打开的db,否则无法执行open
db.close();
//表不完整
// Delete the database
await deleteDatabase(path);
db = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
// When creating the db, create the table
await db.execute(SqlTable.sql_createTable_course);
await db.execute(SqlTable.sql_createTable_user);
print('db created version is $version');
}, onOpen: (Database db) async {
print('new db opened');
});
} else {
print("Opening existing database");
}
}
}