索引优化
- 索引的作用:在SQLite中,索引可以显著提升查询性能。通过在经常用于查询条件的列上创建索引,数据库在执行查询时能够更快地定位到所需数据,减少全表扫描的开销。
- 创建索引示例:
Future<void> createIndex() async {
final database = await openDatabase(
'your_database.db',
version: 1,
onCreate: (Database db, int version) async {
// 创建表
await db.execute('''
CREATE TABLE your_table (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
''');
// 创建索引,假设经常根据name查询
await db.execute('CREATE INDEX idx_name ON your_table (name)');
},
);
}
事务处理
- 事务的概念:事务是一组SQL操作,这些操作要么全部成功执行,要么全部失败回滚。在批量数据读写时,使用事务可以减少磁盘I/O次数,提高整体性能,同时保证数据的一致性。
- 事务处理示例:
Future<void> batchInsert() async {
final database = await openDatabase(
'your_database.db',
version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
CREATE TABLE your_table (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
''');
},
);
await database.transaction((txn) async {
List<Map<String, dynamic>> dataList = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 30},
// 更多数据
];
for (var data in dataList) {
await txn.insert('your_table', data);
}
});
}
缓存优化
- 缓存的意义:在Flutter应用中,缓存可以减少对SQLite数据库的频繁访问。对于一些不经常变化且查询频繁的数据,将其缓存到内存中,可以快速响应读取请求,提升应用的响应速度。
- 简单内存缓存示例:
class DataCache {
static Map<int, Map<String, dynamic>> _cache = {};
static Future<Map<String, dynamic>?> getFromCache(int id) async {
return _cache[id];
}
static void putInCache(int id, Map<String, dynamic> data) {
_cache[id] = data;
}
}
// 使用缓存读取数据示例
Future<Map<String, dynamic>?> readDataWithCache(int id) async {
var data = await DataCache.getFromCache(id);
if (data != null) {
return data;
}
final database = await openDatabase(
'your_database.db',
version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
CREATE TABLE your_table (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
''');
},
);
data = await database.query('your_table', where: 'id =?', whereArgs: [id]);
if (data.isNotEmpty) {
DataCache.putInCache(id, data.first);
return data.first;
}
return null;
}