Database
- Dart course
- Advanced
- Lesson 44/83
- 5 min
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.
Practice 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().
Starter code
// import the sqflite package
// define openDb (open users.db, create users table, return Database)
void main() async {
// print the connection info
}Sample 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();
}Expected output
Database: users.db Table: users (id, name)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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;
}
Future<Database> openDb() async {
final db = await openDatabase('users.db');
await db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
return db;
}
Explanation: Future<Database> return type marks the connection.
2 What does openDatabase return?
- void
- String
- int
- Database Correct answer
Explanation: openDatabase returns a Database object.
3 Match the Database parts
| Term | Meaning |
|---|---|
Database |
Connection object |
openDatabase |
Opens |
db.close |
Closes |
await |
Waits asynchronously |