CodeBlanks Logo Icon CodeBlanks

CRUD

Learn CRUD operations with sqflite.

CRUD operations

CRUD stands for four basic database operations: Create, Read, Update, Delete. sqflite offers these via db.insert, db.query, db.update and db.delete.

Example: await db.insert('notes', {'title': 'Merhaba'}); adds a new row. final rows = await db.query('notes'); pulls all rows. Each row comes as a Map<String, dynamic>; rows[0]['title'] gives the first row's title.

Inserting and querying rows

To add a row you call db.insert('table', map). The map binds column names to values; for example {'title': 'Merhaba', 'body': 'İlk notum'}.

To query rows you use db.query('table'). The result is a List<Map<String, dynamic>>. rows[0]['title'] gives the first row's title column. In this lesson we will write a crudDemo function: it inserts a note, queries all notes and prints the first note's title.

Practice Insert and query a note

The code below imports sqflite and main opens a Database. Define crudDemo(Database db): insert a note with db.insert('notes', {'title': 'Merhaba', 'body': 'First note'}), query all notes with db.query('notes') and print the first note's title with print('First note: ${rows[0]['title']}'). main already has print('CRUD: insert + query'); add the crudDemo(db) call.

Starter code

main.dart
import 'package:sqflite/sqflite.dart';

Future<void> crudDemo(Database db) async {
  // insert a note (db.insert) and query all notes (db.query)
  // print the first note's title
}

void main() async {
  print('CRUD: insert + query');
  final db = await openDatabase('notes.db');
  await crudDemo(db);
  await db.close();
}

Sample solution

main.dart
import 'package:sqflite/sqflite.dart';

Future<void> crudDemo(Database db) async {
  await db.insert('notes', {'title': 'Merhaba', 'body': 'First note'});
  final rows = await db.query('notes');
  print('First note: ${rows[0]["title"]}');
}

void main() async {
  print('CRUD: insert + query');
  final db = await openDatabase('notes.db');
  await crudDemo(db);
  await db.close();
}

Expected output

CRUD: insert + query
First note: Merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the CRUD methods

Term Meaning
db.insert Create
db.query Read
db.update Update
db.delete Delete

2 Which method adds a new row?

  • db.insert Correct answer
  • db.delete
  • db.update
  • db.query

Explanation: db.insert adds a new row (Create).

3 The db.insert call

Question
await db.____('notes', {'title': 'Merhaba', 'body': 'First note'});
Answer
await db.insert('notes', {'title': 'Merhaba', 'body': 'First note'});

Explanation: db.insert('notes', {...}) adds a new row.

All lessons in Advanced