Dart
Database
Learn connection and queries with Database.
The Database connection
The openDatabase call returns a Database object. This object represents the connection; all queries go through it. It has db.query, db.insert, db.update, db.delete and db.execute methods.
When done you close the connection with await db.close(). Leaving a connection open causes resource leaks. So either close at the end of the setup function or leave it to the caller. In this lesson we highlight the Database type.
Closing the connection
Once a Database connection is opened it holds system resources (file handles, memory). When done you release them with await db.close(). This matters especially in long-running applications.
Example pattern: final db = await openDb(); ... await db.close();. The setup function returns the connection; the caller uses and closes it. This keeps responsibility clear. In this lesson we will write openDb to return a Database.
Exercise The openDb function
Add import 'package:sqflite/sqflite.dart';. Define Future<Database> openDb() async { ... }: open with openDatabase('users.db'), create the table with db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)') and return db. In main add print('Database: users.db') and print('Table: users (id, name)'), then call await openDb().
Show example solution
import 'package:sqflite/sqflite.dart';
Future<Database> openDb() async {
final db = await openDatabase('users.db');
await db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
return db;
}
void main() async {
print('Database: users.db');
print('Table: users (id, name)');
await openDb();
}
Test yourself
-
The Database type
Future<____> openDb() async {
final db = await openDatabase('users.db');
await db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
return db;
}
Show answer
Future<Database> openDb() async {
final db = await openDatabase('users.db');
await db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
return db;
}
-
What does openDatabase return?
Show answer
Database — openDatabase returns a Database object.
-
Match the Database parts
- Database
- Connection object
- openDatabase
- Opens
- db.close
- Closes
- await
- Waits asynchronously
Next lesson: CRUD