CodeBlanks Logo Icon CodeBlanks

openDatabase

Create a database with openDatabase.

Creating a table

To create a table, you run a CREATE TABLE SQL query with db.execute. The onCreate callback of openDatabase is called on first open.

await openDatabase(
  'app.db',
  version: 1,
  onCreate: (db, version) async {
    await db.execute(
      'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)'
    );
  },
);

This query creates the table once.

onCreate callback

onCreate is called when the database is created for the first time. Here you define the tables. The version parameter specifies the table version; on change onUpgrade is triggered.

onCreate: (db, version) async {
  await db.execute('CREATE TABLE ...');
},

onCreate runs only once.

Practice Create the kullanicilar table

In the ac async method, call openDatabase. In the onCreate callback, run the query 'CREATE TABLE kullanicilar (id INTEGER PRIMARY KEY, isim TEXT)' with db.execute. In main, await ac and print 'tablo oluşturuldu'.

Starter code

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

Future<void> ac() async {
  // openDatabase ile onCreate içinde tablo oluştur
}

void main() async {
  await ac();
  print('tablo oluşturuldu');
}

Sample solution

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

Future<void> ac() async {
  await openDatabase(
    'uygulama.db',
    version: 1,
    onCreate: (db, version) async {
      await db.execute(
        'CREATE TABLE kullanicilar (id INTEGER PRIMARY KEY, isim TEXT)'
      );
    },
  );
}

void main() async {
  await ac();
  print('tablo oluşturuldu');
}

Expected output

tablo oluşturuldu

Questions and answers

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

1 Which SQL command is used to create a table?

  • DELETE FROM
  • CREATE TABLE Correct answer
  • SELECT
  • INSERT INTO

Explanation: The CREATE TABLE command defines and creates a table with its columns.

2 Run the CREATE TABLE query

Question
await db.____(
  'CREATE TABLE kullanicilar (id INTEGER PRIMARY KEY, isim TEXT)'
);
Answer
await db.execute(
  'CREATE TABLE kullanicilar (id INTEGER PRIMARY KEY, isim TEXT)'
);

Explanation: SQL commands such as CREATE TABLE are run with db.execute; it is used for queries that do not return a value.

3 Table creation parts

Term Meaning
CREATE TABLE SQL command creating the table
onCreate Callback called on first open
execute Method running SQL command
version Parameter specifying table version

All lessons in Intermediate