我正在构建一个应用程序,用户可以在其中创建多个项目。我希望每个项目都有其唯一的数据库,因为虽然列(将有 6-7 列)名称相同,但新项目的列下的值会有所不同。
每次用户创建新项目时如何创建新的 SQFlite 数据库?
还是有其他更好的方法来实现这一目标?
如果您想通过它,这是我手动创建的数据库的代码:
class DatabaseHelper {
static final DatabaseHelper _instance = new DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
final String tableUser = "userTable";
final String columnId = "id";
final String columnRuns = "runs";
static Database _db;
Future<Database> get db async {
if (_db != null) {
return _db;
}
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async {
Directory documentDirectory = await getApplicationDocumentsDirectory();
String path = join(documentDirectory.path,
"maindbnew.db"); //home://directory/files/maindb.db
var ourDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return ourDb;
}
void _onCreate(Database db, int newVersion) async {
await db.execute(
"CREATE TABLE $tableUser($columnId INTEGER PRIMARY KEY, $columnRuns INTEGER)");
}
//CRUD - CREATE, READ, UPDATE, DELETE
//Insertion
Future<int> saveUser(User user) async {
var dbClient = await db;
int res = await dbClient.insert("$tableUser", user.toMap());
return res;
}
//Get Users
Future<List> getAllUsers() async {
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM $tableUser");
return result.toList();
}
Future<int> getCount() async {
var dbClient = await db;
return Sqflite.firstIntValue(
await dbClient.rawQuery("SELECT COUNT(*) FROM $tableUser"));
}
Future<User> getUser(int id) async {
var dbClient = await db;
var result = await dbClient
.rawQuery("SELECT * FROM $tableUser WHERE $columnId = $id");
if (result.length == 0) return null;
return new User.fromMap(result.first);
}
Future<int> deleteUser(int id) async {
var dbClient = await db;
return await dbClient
.delete(tableUser, where: "$columnId = ?", whereArgs: [id]);
}
Future<int> updateUser(User user) async {
var dbClient = await db;
return await dbClient.update(tableUser, user.toMap(),
where: "$columnId = ?", whereArgs: [user.id]);
}
Future close() async {
var dbClient = await db;
return dbClient.close();
}
}
class User {
int _runs;
int _id;
User(this._runs);
User.map(dynamic obj) {
this._runs = obj['runs'];
this._id = obj['id'];
}
int get runs => _runs;
int get id => _id;
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
map["runs"] = _runs;
if (id != null) {
map["id"] = _id;
}
return map;
}
User.fromMap(Map<String, dynamic> map) {
this._runs = map["runs"];
this._id = map["id"];
}
}
PS我现在只有一个专栏,我稍后会添加更多。