การผสานรวมฐานข้อมูล SQLite
ผสานรวมฐานข้อมูล SQLite เข้ากับแอป Flutter โดยใช้แพ็กเกจ `sqflite` เพื่อจัดเก็บข้อมูลที่มีโครงสร้างและข้อมูลเชิงสัมพันธ์
การผสานรวมฐานข้อมูล SQLite เป็นบทเรียน Flutter Mobile Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Flutter Mobile Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Storing Data with SQLite
Welcome! In this lesson, we'll learn how to integrate a local database into your Flutter app using SQLite.
SQLite is a lightweight, serverless, self-contained, and transactional relational database engine. It's perfect for storing structured data directly on the user's device without needing a separate server process.
Getting `sqflite` Ready
To use SQLite in Flutter, we rely on the popular sqflite package. It provides a robust interface to SQLite databases.
First, add it (along with path_provider and path for database file management) to your pubspec.yaml file under dependencies:
dependencies:flutter:sdk: fluttersqflite: ^2.3.0path_provider: ^2.1.1path: ^1.8.3
Run flutter pub get in your terminal after adding these.
Database Helper Class
It's a best practice to create a dedicated "helper" class to manage your database operations. This centralizes logic for opening, creating, and executing queries.
This class will typically handle:
- Initializing and opening the database connection.
- Creating tables when the database is first opened.
- Providing a single instance (singleton) of the database for the entire application.
- Abstracting direct SQL queries.
Initializing the Database
Let's start building our DatabaseHelper. The openDatabase function is key. It takes the database file path and an onCreate callback for initial setup.
Here's how to open or create your database:
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
// NOTE: getDatabasesPath() requires Flutter context.
// This main method is for demonstration.
// In a real Flutter app, _initDatabase would be called
// from a StatefulWidget or similar.
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _database;
factory DatabaseHelper() {
return _instance;
}
DatabaseHelper._internal();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
// Get the default databases location for the platform
String path = await getDatabasesPath();
String dbPath = join(path, 'item_database.db');
return await openDatabase(
dbPath,
version: 1,
onCreate: (db, version) {
// Table creation logic will go here
print('Database created or opened.');
},
);
}
}
void main() async {
// This main is illustrative. sqflite operations need a
// running Flutter app context to fully function (e.g. for getDatabasesPath).
// When run in a Flutter app, DatabaseHelper().database
// would ensure the DB is initialized.
print('DatabaseHelper class defined.');
}
Creating Your First Table
Inside the onCreate callback of _initDatabase, we define our database schema using standard SQL. Let's create a simple items table.
Each item will have an id (primary key), a name (text), and a quantity (integer).
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _database;
factory DatabaseHelper() { return _instance; }
DatabaseHelper._internal();
Future<Database> get database async { if (_database != null) return _database!; _database = await _initDatabase(); return _database!; }
Future<Database> _initDatabase() async {
String path = await getDatabasesPath();
String dbPath = join(path, 'item_database.db');
return await openDatabase(dbPath, version: 1,
onCreate: (db, version) async {
// SQL to create the items table
await db.execute(
'''
CREATE TABLE items(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
quantity INTEGER
)
'''
);
print('Table "items" created successfully.');
},
);
}
}
void main() async {
// This main is illustrative. In a Flutter app,
// calling DatabaseHelper().database would trigger
// _initDatabase and the onCreate callback.
print('Database helper configured for table creation.');
}
Creating a Data Model
To work easily with database records, define a Dart class that mirrors your table's structure. This helps map data between Dart objects and database rows (which are typically represented as Map).
Here's our Item model with toMap() and fromMap() methods:
class Item {
final int? id;
final String name;
final int quantity;
Item({this.id, required this.name, required this.quantity});
// Convert an Item into a Map. Keys must match DB column names.
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'quantity': quantity,
};
}
// Create an Item object from a Map (database row).
static Item fromMap(Map<String, dynamic> map) {
return Item(
id: map['id'],
name: map['name'],
quantity: map['quantity'],
);
}
@override
String toString() {
return 'Item(id: $id, name: $name, quantity: $quantity)';
}
}
void main() {
final myItem = Item(id: 1, name: 'Apple', quantity: 5);
print('Created Item: ${myItem.toString()}');
print('Converted to Map: ${myItem.toMap()}');
final itemMap = {'id': 2, 'name': 'Banana', 'quantity': 3};
final itemFromMap = Item.fromMap(itemMap);
print('Item from Map: ${itemFromMap.toString()}');
}
Inserting Data
Now let's add a method to our DatabaseHelper to insert new items. The insert method takes the table name and a Map (from our Item.toMap()).
It returns the id of the newly inserted row.
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
// Item class (from previous scene, for self-containment)
class Item {
final int? id; final String name; final int quantity;
Item({this.id, required this.name, required this.quantity});
Map<String, dynamic> toMap() { return {'id': id, 'name': name, 'quantity': quantity}; }
static Item fromMap(Map<String, dynamic> map) { return Item(id: map['id'], name: map['name'], quantity: map['quantity']); }
@override
String toString() { return 'Item(id: $id, name: $name, quantity: $quantity)'; }
}
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _database;
factory DatabaseHelper() { return _instance; }
DatabaseHelper._internal();
Future<Database> get database async { if (_database != null) return _database!; _database = await _initDatabase(); return _database!; }
Future<Database> _initDatabase() async {
String path = await getDatabasesPath();
String dbPath = join(path, 'item_database.db');
return await openDatabase(dbPath, version: 1,
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE items(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, quantity INTEGER)
''');
},
);
}
Future<int> insertItem(Item item) async {
final db = await database;
return await db.insert(
'items',
item.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace, // Replace if ID exists
);
}
}
void main() async {
// Illustrative main. In a Flutter app, you'd call:
// final dbHelper = DatabaseHelper();
// final newItem = Item(name: 'Milk', quantity: 2);
// int id = await dbHelper.insertItem(newItem);
// print('Inserted item with id: $id');
print('Item insertion logic defined in DatabaseHelper.');
}
Querying Data
To read data, use the query method. It returns a List, which you then convert back into your Dart Item objects using Item.fromMap().
You can query all items or specific ones using where clauses.
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
// Item class (for self-containment)
class Item {
final int? id; final String name; final int quantity;
Item({this.id, required this.name, required this.quantity});
Map<String, dynamic> toMap() { return {'id': id, 'name': name, 'quantity': quantity}; }
static Item fromMap(Map<String, dynamic> map) { return Item(id: map['id'], name: map['name'], quantity: map['quantity']); }
@override
String toString() { return 'Item(id: $id, name: $name, quantity: $quantity)'; }
}
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _database;
factory DatabaseHelper() { return _instance; }
DatabaseHelper._internal();
Future<Database> get database async { if (_database != null) return _database!; _database = await _initDatabase(); return _database!; }
Future<Database> _initDatabase() async {
String path = await getDatabasesPath();
String dbPath = join(path, 'item_database.db');
return await openDatabase(dbPath, version: 1,
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE items(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, quantity INTEGER)
''');
},
);
}
Future<List<Item>> getItems() async {
final db = await database;
// Query all the items from the table
final List<Map<String, dynamic>> maps = await db.query('items');
// Convert the List<Map<String, dynamic>> into a List<Item>.
return List.generate(maps.length, (i) {
return Item.fromMap(maps[i]);
});
}
}
void main() async {
// Illustrative main. In a Flutter app, you'd call:
// final dbHelper = DatabaseHelper();
// await dbHelper.insertItem(Item(name: 'Bread', quantity: 1));
// final items = await dbHelper.getItems();
// print('Retrieved items: $items');
print('Item query logic defined in DatabaseHelper.');
}
Updating Data
To change an existing record, use the update method. You provide the table name, the new data as a Map, and a where clause to specify which record(s) to update.
Always use whereArgs with placeholders (?) to pass values safely and prevent SQL injection.
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
// Item class (for self-containment)
class Item {
final int? id; final String name; final int quantity;
Item({this.id, required this.name, required this.quantity});
Map<String, dynamic> toMap() { return {'id': id, 'name': name, 'quantity': quantity}; }
static Item fromMap(Map<String, dynamic> map) { return Item(id: map['id'], name: map['name'], quantity: map['quantity']); }
@override
String toString() { return 'Item(id: $id, name: $name, quantity: $quantity)'; }
}
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _database;
factory DatabaseHelper() { return _instance; }
DatabaseHelper._internal();
Future<Database> get database async { if (_database != null) return _database!; _database = await _initDatabase(); return _database!; }
Future<Database> _initDatabase() async {
String path = await getDatabasesPath();
String dbPath = join(path, 'item_database.db');
return await openDatabase(dbPath, version: 1,
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE items(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, quantity INTEGER)
''');
},
);
}
Future<int> updateItem(Item item) async {
final db = await database;
return await db.update(
'items',
item.toMap(),
where: 'id = ?', // Specify which item to update
whereArgs: [item.id],
);
}
}
void main() async {
// Illustrative main. In a Flutter app, you'd call:
// final dbHelper = DatabaseHelper();
// // Assume item with id 1 exists
// var updatedItem = Item(id: 1, name: 'Milk', quantity: 3);
// int count = await dbHelper.updateItem(updatedItem);
// print('Updated $count item(s).');
print('Item update logic defined in DatabaseHelper.');
}
Deleting Data
To remove records from your database, use the delete method. Similar to update, you provide the table name and a where clause with whereArgs to specify which records to remove.
This method returns the number of rows deleted.
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
// Item class (for self-containment)
class Item {
final int? id; final String name; final int quantity;
Item({this.id, required this.name, required this.quantity});
Map<String, dynamic> toMap() { return {'id': id, 'name': name, 'quantity': quantity}; }
static Item fromMap(Map<String, dynamic> map) { return Item(id: map['id'], name: map['name'], quantity: map['quantity']); }
@override
String toString() { return 'Item(id: $id, name: $name, quantity: $quantity)'; }
}
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _database;
factory DatabaseHelper() { return _instance; }
DatabaseHelper._internal();
Future<Database> get database async { if (_database != null) return _database!; _database = await _initDatabase(); return _database!; }
Future<Database> _initDatabase() async {
String path = await getDatabasesPath();
String dbPath = join(path, 'item_database.db');
return await openDatabase(dbPath, version: 1,
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE items(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, quantity INTEGER)
''');
},
);
}
Future<int> deleteItem(int id) async {
final db = await database;
return await db.delete(
'items',
where: 'id = ?',
whereArgs: [id],
);
}
}
void main() async {
// Illustrative main. In a Flutter app, you'd call:
// final dbHelper = DatabaseHelper();
// // Assume item with id 1 exists
// int count = await dbHelper.deleteItem(1);
// print('Deleted $count item(s).');
print('Item deletion logic defined in DatabaseHelper.');
}
SQLite Operations Quiz
Consider an items table with columns id (INTEGER), name (TEXT), and quantity (INTEGER).
Which sqflite method would you use to retrieve all items where the quantity is greater than 10?
Recap: SQLite & `sqflite`
Great job! You've learned the fundamentals of integrating SQLite into your Flutter app using the sqflite package.
Key takeaways:
- SQLite is a lightweight, local, relational database.
- The
sqflitepackage provides Dart APIs for SQLite. - A
DatabaseHelperclass centralizes database operations like creating, opening, and managing tables. - You can perform standard CRUD (Create, Read, Update, Delete) operations using
insert,query,update, anddeletemethods. - Using a data model class (like
Item) simplifies mapping data between Dart objects and database rows.
This knowledge is crucial for building robust Flutter apps with local data persistence!
คำถามที่พบบ่อย
บทเรียน “การผสานรวมฐานข้อมูล SQLite” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การผสานรวมฐานข้อมูล SQLite” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Flutter Mobile Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การผสานรวมฐานข้อมูล SQLite”
ผสานรวมฐานข้อมูล SQLite เข้ากับแอป Flutter โดยใช้แพ็กเกจ `sqflite` เพื่อจัดเก็บข้อมูลที่มีโครงสร้างและข้อมูลเชิงสัมพันธ์ คุณปฏิบัติ Flutter Mobile Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Flutter Mobile Development หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Flutter Mobile Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การผสานรวมฐานข้อมูล SQLite” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Flutter Mobile Development นี้ได้ไหม
ได้ บทเรียน Flutter Mobile Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- Shared Preferences สำหรับข้อมูล
- การผสานรวมฐานข้อมูล SQLite
- การดำเนินการกับระบบไฟล์
- Hive และพื้นที่จัดเก็บภายในแบบ NoSQL