2023-12-19|閱讀時間 ‧ 約 25 分鐘

[Flutter]SQLite

加入套件

在pubspec.yaml添加sqflite與path_provider。


建立數據模型

  • id:識別欄位,唯一值為整數資料類型
  • name:存放名字為字串資料類型
class People {
final int? id;
final String? name;

Student({this.id, this.name});

Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
};
}
}


建立資料庫接口

class DatabaseHelper {
static final _databaseName = "your_database_name.db";
static final _databaseVersion = 1;

static final table = 'your_table';


//Singleton 單例模式,確保一個類別只有一個實例
DatabaseHelper._privateConstructor();

static final DatabaseHelper instance = DatabaseHelper._privateConstructor();


static Database? _database;

Future<Database?> get database async {
if (_database != null) return _database;
_database = await _initDatabase();
return _database;
}

_initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, _databaseName);
return await openDatabase(path,
version: _databaseVersion, onCreate: _onCreate);
}

Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $table (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
)
''');
}


Future<int> insert(Map<String, dynamic> row) async {
Database? db = await instance.database;
return await db!.insert(table, row);
}


Future<List<Map<String, dynamic>>> queryAllRows() async {
Database? db = await instance.database;
return await db!.query(table);
}


Future<int?> queryRowCount() async {
Database? db = await instance.database;
return Sqflite.firstIntValue(
await db!.rawQuery('SELECT COUNT(*) FROM $table'));
}

Future<int> update(Map<String, dynamic> row) async {
Database? db = await instance.database;
int id = row['id'];
return await db!.update(table, row, where: 'id = ?', whereArgs: [id]);
}

Future<int> delete(int id) async {
Database? db = await instance.database;
return await db!.delete(table, where: 'id = ?', whereArgs: [id]);
}
}








分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.