Utilizing the 'create' function in sqlite each time I need to run a query

I've been diving into SQLite within the Ionic framework and have pieced together some code based on examples I've encountered.

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';

@IonicPage()
@Component({
  selector: 'page-sqlite',
  templateUrl: 'sqlite.html',
})
export class SqlitePage {

  constructor(public navCtrl: NavController, public navParams: NavParams, public sqlite: SQLite) {
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    })
    .then((db: SQLiteObject) => {
      db.executeSql('create table if not exists danceMoves(name VARCHAR(32))', {})
        .then(() => console.log('Executed SQL'))
        .catch(e => console.log(e));
    })
    .catch(e => console.log(e));
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad SqlitePage');
  }

  navigateToRegisterPage(){
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    })
    .then((db: SQLiteObject) => {
      db.executeSql('SELECT * FROM danceMoves', [])
        .then(res => {
          console.log(res);
          console.log('The SELECT has been succesfully executed');
        })
    })
  }

}

In the navigateToRegisterPage() function, I perform a SELECT query after calling this.sqlite.create. Do I need to do this every time I want to execute a query, or is there a more efficient approach?

Answer №1

It is unnecessary to create the table every time you need to access data. Take a look at the following code snippet, which retrieves data from the SQLite database:

fetchData(tableName, fields: Array<{}>): Promise<any> {

    let value: any = false;
    let field = "";
    for (var i = 0; i < fields.length; i++) {
        console.log("------- Value in the Fields Array is -------" + fields[i]);
        field += fields[i] + " " + 'TEXT,';
    }
    let query = "CREATE TABLE IF NOT EXISTS " + tableName + "(rowid INTEGER PRIMARY KEY,id INTEGER NOT NULL UNIQUE," + field + "col INT)";

    this.db.executeSql(query, {}).then(result => {
        console.log('SQL Executed Successfully')
    }).catch(error => console.log(error));

    this.db.executeSql("SELECT * FROM " + tableName, {}).then(result => {
        value = result;
    })

    return value;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Custom Angular 2 decorator designed for post-RC4 versions triggers the 'Multiple Components' exception

Currently, I am in the process of updating my Ionic 2 component known as ionic2-autocomplete. This component was initially created for RC.4 and earlier iterations, and now I am working on migrating it to Angular 2 final. One key aspect of the original des ...

The received data object appears to be currently undefined

I am currently using MapBox to display multiple coordinates on a map, but I am encountering an issue where the longitude and latitude values in my return object are showing up as undefined. Could there be a missing configuration that is preventing the data ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

Can the Rxjs library's Observables of() function be used to output multiple values?

I am inquiring about this because I came across in the Angular documentation that of(HEROES) returns an Observable<Hero[]> which emits a single value - an array of mock heroes. If I cannot use of(), do you have any alternative suggestions for me? I ...

An error occurs when attempting to use object mapping and the rest operator in a return statement due to

I've encountered a type mismatch error in my TypeScript project using Prisma while attempting to return an object with mapped properties in the getPool method. Let's take a look at the code snippet causing the issue: public async getPool({ id, v ...

NestJS Bull queues - Failing to secure job completion with a lock

I am currently utilizing Bull in combination with NestJS to manage a jobs queue. Within the process handler, I aim to designate a job as failed instead of completed. However, it appears - after carefully reviewing the documentation as well - that the Job#m ...

Angular2 had a delay in processing the 'mouse wheel' input event for x milliseconds because the main thread was occupied

Currently, I am working with Angular2 (r.2.0.0) along with typescript (v.1.8.10). I have encountered an issue where Chrome does not respond while scrolling and displays a warning message stating: "Handling of 'mouse wheel' input event was delayed ...

Clicking on the React Bootstrap Checkbox within the Nav component does not trigger a rerender of the NavItem component

Encountering an unusual issue while using a Nav and NavItem with a Checkbox from React Bootstrap. What I've noticed is that when clicking directly on the checkbox instead of the NavItem button, the checkbox does not re-render correctly even though my ...

Having trouble with Ionic on Safari and iOS 11 when using the ServiceStack Client

My Ionic app is encountering issues when calling any webservice method (ServiceStack) on Safari 11.1 (13605.1.33.1.2). The same problem occurs when running on iOS 11 device or simulator, as shown in the attached image. The app functions properly on Chrome ...

Guide to setting data types for [key, value] pairs within a forEach iteration

I am currently encountering a typescript syntax error in my project that is indicating the need to define the prodStatus variable... const products = { 1: {isUpdating: false, qty: 2}, 2: {isUpdating: true, qty: 4} } const updatingProducts: Array< ...

Tips for retrieving an object from an array with Angular and Firestore

Currently, I am attempting to retrieve an object from Firestore using the uid so that I can return a specific object as a value. I have implemented a function in order to obtain the object 'Banana'. getFruit(fruitUid: string, basketUid: string) ...

Setting up Typescript: The Guide to Declaring a Dependent Property

In my current project, I am working on creating a declaration file for the quadstore library. This library has a class that requires a constructor parameter called contextKey. The value of this parameter determines the name of a field on method arguments. ...

Refreshing Angular 4 route upon modification of path parameter

I have been struggling to make the subscribe function for the params observable work in my Angular project. While I have successfully implemented router.events, I can't seem to get the subscription for params observable working. Can anyone point out w ...

Using TypeScript arrow function parentheses in the filter function

If I have an array of movie objects like this: const movies: Movie[] = [ movie1, movie2, movie3, movie4 ]; And if I want to remove a specific movie from the array, such as movie2, I can use the following code: movies = movies.filter( m => m !== ...

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

Steps for sending an image to Cloudinary using the fetch API

Struggling to figure out how to successfully upload a file to Cloudinary using fetch on my front-end. After consulting the documentation and various StackOverflow threads, I'm still facing a frustrating 400 error: export async function uploadImageToCl ...

Retrieve the time zone setting from either my browser or server, and then incorporate it into angular2-highcharts

My current timezone setup is done manually using the timezoneOffset function from the Highcharts API. I am currently in GMT+2 so I set it to -2 * 60. However, I encountered an issue where my setup would not work properly when the hour changes in October. T ...

Troubleshooting a Missing Call Display Issue in Angular2 API

Greetings, I am a new web developer and I have been tasked with creating a prototype Inventory Page using Angular2. Please bear with me as my code may not be perfect. In the snippet below, you'll notice that we are calling our base back-end API (&apo ...

Utilize TypeScript File array within the image tag in HTML with Angular 2

I am in the process of developing a web application that allows users to upload CSV data and images, which are then displayed on the application. However, I have encountered an issue where I am unable to display the imported images. The images are imported ...

"Typescript throws a mysterious 'Undefined value' error post-assignment

I'm currently working on a task to fetch my customer's branding information based on their Id using Angular. First, I retrieve all the customer data: this.subscription = this.burstService.getBurst().subscribe(async(response) => { if (r ...