CodeBlanks Logo Icon CodeBlanks

CREATE TABLE

Create a table with db.execute.

Inserting a record

To insert a record into a table, you use the db.insert method or an INSERT INTO SQL query. db.insert takes a Map.

await db.insert('users', {
  'name': 'Ayşe',
});

insert returns the id of the inserted row.

insert return value

db.insert returns the id of the inserted row as an int. If PRIMARY KEY auto-increments, this id is the new row's id.

final id = await db.insert('users', {
  'name': 'Ayşe',
});
print('inserted id: $id');

This id can be used in later operations.

Practice Insert a user and print id

In the Veritabani class, write a db field and a kullaniciEkle method. kullaniciEkle should call db.insert('kullanicilar', {'isim': isim}) and return the id. In main, call kullaniciEkle('Ayşe') and print 'id: $id'.

Starter code

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

class Veritabani {
  late Database db;

  Future<void> ac() async {
    db = await openDatabase('uygulama.db');
  }

  // kullaniciEkle metodu ekle
}

void main() async {
  final vt = Veritabani();
  await vt.ac();
  // kullaniciEkle'yi çağır ve id'yi yazdır
}

Sample solution

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

class Veritabani {
  late Database db;

  Future<void> ac() async {
    db = await openDatabase('uygulama.db');
  }

  Future<int> kullaniciEkle(String isim) async {
    final id = await db.insert('kullanicilar', {'isim': isim});
    return id;
  }
}

void main() async {
  final vt = Veritabani();
  await vt.ac();
  final id = await vt.kullaniciEkle('Ayşe');
  print('id: $id');
}

Expected output

id: 1

Questions and answers

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

1 What is given as the second parameter to db.insert?

  • A String
  • A List
  • A Map holding column values Correct answer
  • An int

Explanation: The second parameter of db.insert is a Map mapping column names to their values.

2 Add a record with db.insert

Question
await db.____('kullanicilar', {
  'isim': 'Ayşe',
});
Answer
await db.insert('kullanicilar', {
  'isim': 'Ayşe',
});

Explanation: The db.insert method adds data as a Map to the table; it returns the id of the inserted row.

3 Insert record parts

Term Meaning
db.insert Method inserting a record
Map Structure holding column values
id Primary key of inserted row
kullanicilar Table where record is added

All lessons in Intermediate