一:添加sqflite和path_provider依賴庫(kù)
dependencies:
flutter:
sdk: flutter
sqflite: ^2.3.0 #數(shù)據(jù)庫(kù)
path_provider: ^2.1.0 #文件路徑獲取
二:創(chuàng)建數(shù)據(jù)庫(kù)單類(lèi)-創(chuàng)建多張表單樣例
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
class DatabaseHelper {
static final _dbName = 'myDatabase.db';
static final _dbVersion = 1;
// 表名
static final userTable = 'users';
static final productTable = 'products';
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database;
Future<Database> get database async => _database ??= await _initDatabase();
_initDatabase() async {
var documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, _dbName);
return await openDatabase(path, version: _dbVersion, onCreate: _onCreate, onUpgrade: _onUpgrade);
}
Future _onCreate(Database db, int version) async {
// 創(chuàng)建users表
await db.execute('''
CREATE TABLE $userTable (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
password TEXT NOT NULL
)
''');
// 創(chuàng)建products表
await db.execute('''
CREATE TABLE $productTable (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price REAL NOT NULL
)
''');
}
// 更新數(shù)據(jù)庫(kù)結(jié)構(gòu)時(shí)使用的方法
Future _onUpgrade(Database db, int oldVersion, int newVersion) async {
if (oldVersion < newVersion) {
// 執(zhí)行數(shù)據(jù)庫(kù)升級(jí)相關(guān)的操作
if (oldVersion == 1) {
// 從版本1升級(jí)到版本2: 添加新表orders
await db.execute('''
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
user_id INTEGER,
total REAL NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
''');
}
// 如果有更多的版本更新膏执,可以繼續(xù)添加else if語(yǔ)句來(lái)處理
// 例如箭券,如果你想要從版本2升級(jí)到版本3毫炉,你可以這樣做:
/*
else if (oldVersion == 2) {
// 從版本2升級(jí)到版本3: 添加新列到現(xiàn)有表
await db.execute('ALTER TABLE users ADD COLUMN email TEXT');
}
*/
}
}
// 增刪改查示例(以u(píng)sers表為例)
Future<int> insertUser(Map<String, dynamic> row) async {
Database db = await instance.database;
return await db.insert(userTable, row);
}
Future<List<Map<String, dynamic>>> queryAllUsers() async {
Database db = await instance.database;
return await db.query(userTable);
}
Future<int> updateUser(Map<String, dynamic> row) async {
Database db = await instance.database;
int id = row['id'];
return await db.update(userTable, row, where: 'id = ?', whereArgs: [id]);
}
Future<int> deleteUser(int id) async {
Database db = await instance.database;
return await db.delete(userTable, where: 'id = ?', whereArgs: [id]);
}
// 可以添加相似的方法來(lái)處理products表的增刪改查
}
三:使用方法
void addUser() async {
Map<String, dynamic> row = {
'username': 'Alice',
'password': 'password123'
};
final id = await DatabaseHelper.instance.insertUser(row);
print('Inserted user with id: $id');
}
void getAllUsers() async {
final allRows = await DatabaseHelper.instance.queryAllUsers();
print('All users:');
allRows.forEach((row) => print(row));
}
void updateUser(int id) async {
Map<String, dynamic> row = {
'id': id,
'username': 'Bob',
'password': 'newpassword'
};
final rowsAffected = await DatabaseHelper.instance.updateUser(row);
print('Updated $rowsAffected row(s)');
}
void deleteUser(int id) async {
final rowsDeleted = await DatabaseHelper.instance.deleteUser(id);
print('Deleted $rowsDeleted row(s)');
}
注意:在執(zhí)行任何升級(jí)操作之前萍肆,為了安全起見(jiàn),最好進(jìn)行數(shù)據(jù)備份