Technology Encyclopedia Home >How to use database in Ionic?

How to use database in Ionic?

To use a database in Ionic, you typically leverage a client-side database solution like SQLite or integrate with a cloud-based database service. For client-side storage, Ionic provides plugins such as cordova-sqlite-storage that allow you to store data locally on the device.

Example of using SQLite in Ionic:

  1. Install the SQLite plugin:

    ionic cordova plugin add cordova-sqlite-storage
    npm install @ionic-native/sqlite
    
  2. Initialize and use the database in your Ionic app:

    import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';
    
    constructor(private sqlite: SQLite) {}
    
    async createDatabase() {
      try {
        const db: SQLiteObject = await this.sqlite.create({
          name: 'data.db',
          location: 'default'
        });
        return db;
      } catch (error) {
        console.log('Error creating database', error);
      }
    }
    
    async addData(db: SQLiteObject, name: string, age: number) {
      try {
        await db.executeSql('CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)', []);
        await db.executeSql('INSERT INTO people (name, age) VALUES (?, ?)', [name, age]);
      } catch (error) {
        console.log('Error adding data', error);
      }
    }
    

For cloud-based solutions, you can integrate with services like Tencent Cloud's Cloud Database products. For instance, Tencent Cloud's CloudDB for MySQL or MariaDB allows you to create a managed database service that can be accessed from your Ionic app via APIs.

Example of integrating with a cloud database:

  1. Set up a database on Tencent Cloud.
  2. Use HTTP requests to interact with the database:
    import { HttpClient } from '@angular/common/http';
    
    constructor(private http: HttpClient) {}
    
    async getData() {
      const response = await this.http.get('https://your-tencent-cloud-api-endpoint').toPromise();
      return response;
    }
    
    async addData(name: string, age: number) {
      const body = { name, age };
      const response = await this.http.post('https://your-tencent-cloud-api-endpoint', body).toPromise();
      return response;
    }
    

By using these methods, you can effectively manage and interact with databases in your Ionic applications, whether storing data locally or accessing it from the cloud.