Skip to main content
Skip table of contents

How To Use Database

Overview

A database is an organized collection of structured information, or data, typically stored electronically in a computer system.

Tables are database objects that contain all the data in a database. In tables, data is logically organized in a row-and-column format similar to a spreadsheet. Each row represents a unique record, and each column represents a field in the record. In case of connecting to the Database, you have to know the table and column name when querying its Database.

How to use Database

Define Database

Before you create Database, you must define the Table name and column like this:

CODE
private readonly TABLE_DEMO_COLUMNS = ['columnId', 'demo_data1', , 'demo_data2'];
private readonly TABLE_DEMO_NAME = 'demo';
private readonly COLUMN_ID = 'column-id';

Note: You must define and use the strings as const in order to use it multiple time and avoid any typo.

Get Dart Database System Library

CODE
 import { IDartDatabase, Context, ModuleContext, IToast, Toast} from 'dart-api';
 
 //...
 
 //class {
  private readonly db: IDartDatabase | null;
  this.db = this.moduleContext.getSystemLibrary(Context.DART_DATABASE) as IDartDatabase;

Create Database

After defined, if you don’t have Database, use this command to create a new database:

CODE
  this.db?.createTable(TABLE_DEMO_NAME, TABLE_DEMO_COLUMNS, false);

Then you can save Data using handleSaveDatabase command.

Next, you need to query to check whether data existed or not.

  • If data didn’t exist → Insert new query: this.db.insert

  • If data existed → Update query: this.db.update

CODE
if (queryResult.length > 0) {
  this.db
    ?.update(TABLE_DEMO_NAME, { columnId: COLUMN_ID }, data)
    .then(() => Toast.show(3, 'Success', 'Data saved successfully'));
} else {
  this.db
    ?.insert(TABLE_DEMO_NAME, Object.values(data))
    .then(() => Toast.show(3, 'Success', 'Data saved successfully'));
}

Load the value from the database

If you already have database, you should open the application, query data in the Database and bind it to UI using: this.db.query

Then you can use this command to load the value from database:

CODE
 this.db?.hasTable(TABLE_DEMO_NAME).then((result: boolean) => {
      if (result) {
        this.db
          ?.query(TABLE_DEMO_NAME, TABLE_DEMO_COLUMNS, {
            columnId: COLUMN_ID,
          })
          .then((queryResult) => {
              let demo_data1 = queryResult[0].data['demo_data1'],
              let demo_data2 = queryResult[0].data['demo_data2'],
          });
      }

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.