add sqllite utils
This commit is contained in:
56
lib/config/database_helper.dart
Normal file
56
lib/config/database_helper.dart
Normal file
@@ -0,0 +1,56 @@
|
||||
import 'dart:io';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:path/path.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
class DatabaseHelper {
|
||||
static final DatabaseHelper _instance = DatabaseHelper._internal();
|
||||
factory DatabaseHelper() => _instance;
|
||||
static Database? _database;
|
||||
|
||||
DatabaseHelper._internal();
|
||||
|
||||
Future<Database> get database async {
|
||||
if (_database != null) return _database!;
|
||||
_database = await _initDatabase();
|
||||
return _database!;
|
||||
}
|
||||
|
||||
Future<Database> _initDatabase() async {
|
||||
Directory documentsDirectory = await getApplicationDocumentsDirectory();
|
||||
String path = join(documentsDirectory.path, 'chat.db');
|
||||
return await openDatabase(
|
||||
path,
|
||||
version: 1,
|
||||
onCreate: _onCreate,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _onCreate(Database db, int version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
role TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
timestamp INTEGER DEFAULT (strftime('%s', 'now'))
|
||||
''');
|
||||
}
|
||||
|
||||
// 插入一条消息
|
||||
Future<int> insertMessage(Map<String, dynamic> message) async {
|
||||
Database db = await database;
|
||||
return await db.insert('messages', message);
|
||||
}
|
||||
|
||||
// 获取所有消息(按时间排序)
|
||||
Future<List<Map<String, dynamic>>> getMessages() async {
|
||||
Database db = await database;
|
||||
return await db.query('messages', orderBy: 'timestamp ASC');
|
||||
}
|
||||
|
||||
// 删除所有消息
|
||||
Future<int> clearMessages() async {
|
||||
Database db = await database;
|
||||
return await db.delete('messages');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user