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

Error: Select dropdown placeholder malfunctioning

Even after trying numerous solutions from various forums, I am unable to make the placeholder display in my code. Maybe a fresh perspective can help spot what I might be missing. view image here I have experimented with using "" as the value, as ...

How can I use a string variable in Angular 2 to create a dynamic template URL

@Component({ selector: 'bancaComponent', templateUrl: '{{str}}' }) export class BancaComponent implements OnInit { str: String; constructor(private http: Http) { } ngOnInit(): void { this.str = "./file.component.html"; } An ...

Absolute imports in create-react-app do not function properly when using yarn v2 workspaces alongside typescript

I am currently utilizing yarn v2 workspaces, and within my workspaces, I have a frontend project built using create-react-app / react-scripts. My goal is to enable absolute imports in the frontend application so that I can simply do things like import Butt ...

Error message: "An issue has been encountered within Angular 4 where it is

Thank you for any assistance, I realize this may be a beginner question... but I seem to be missing something and my TypeScript code is error-free. My goal is simple: I want to track which Main Menu Item is currently selected. To achieve this, I have bou ...

Mongoose TypeScript Aggregation error: is not a valid property of type 'any[]'

Attempting to replace a standard mongo call with an aggregate call. The original code that was functional is as follows: const account = await userModel .findOne({ 'shared.username': username }) .exec(); console.log(account._id) The n ...

Utilize the provider within the decorator function

Essentially, the challenge I am facing is passing an authService to the "verifyClient" function within the @WebSocketGateway decorator. Here is how it should look: @WebSocketGateway({ transports: ['websocket'], verifyClient: (info: { req: Inc ...

Issue in VueJs where mutations do not properly save new objects to the state

I am facing an issue with updating my vuex store after modifying my user credentials in a component. Below is the code snippet for reference: mutations: { updateUserState: function(state, user) { state.user = user; }, } actions: { updat ...

What is the process for choosing nested colors from a theme in Material UI?

I have a question regarding how to select a nested style from my theme when creating a Button. Below is the snippet of code that illustrates my dilemma: const buttonStyle: SxProps<Theme> = { '&:hover': { backgroundColor: 'bac ...

How come a Google Maps API component functions properly even without using *NgIf, but fails to work when excluded in Angular 9?

I recently followed the guide provided in this discussion with success. The method outlined worked perfectly for loading search boxes using this component: map.component.html <input id= 'box2' *ngIf="boxReady" class="controls" type="text" p ...

Tips for determining the datatype of a callback parameter based on the specified event name

Let's say we have the following code snippet: type eventType = "ready" | "buzz"; type eventTypeReadyInput = {appIsReady: string}; interface mysdk { on:(event: eventType, cb: (input: eventTypeCallbackInput) => void) => void } mysdk.on("ready", ...

Tips on typing a collection that may hold numerous instances of a particular object

When working with NgRx actions, I need to define the parameter. This parameter is an object that can contain a varying number of specific objects. These objects are already defined in an Interface. export interface CustomDistribution { maxWindowsActive ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

Tslint is notifying that JSX elements without any children must be self-closing to prevent errors [Error]

Recently, I encountered an issue while trying to build my solution using the command npm run build. The error message displayed was: JSX elements with no children must be self-closing. I came across a similar problem on Stack Overflow but unfortunately ...

The type 'Observable' does not contain the properties found in type 'User'

I am trying to retrieve user data from Firestore, but encountering an error The type 'Observable' is missing the following properties from type 'User': email, emailVerified, uidts(2739) user.service.ts import { Injectable } from &apo ...

Fix React/Typescript issue: Exported variable conflicts with name from external module

I am encountering a perplexing issue when using React with Redux and Typescript. The error message I am receiving is unfamiliar to me, and I am unsure how to resolve it. The error states: Exported variable 'rootReducer' has or is using name ...

Minimize the count of switch cases that are not empty

How can I optimize the number of cases in my switch statement to align with SonarQube recommendations? Currently, I have 37 cases in a switch statement, but SonarQube recommends only 30. I believe that my code is functioning correctly, and the issue lies ...

Limit the usage of typescript to ensure that references to properties of 'any' object are verified

I'm facing a situation where I have a JS object called myObject, and it is of type any. Unfortunately, I cannot change the type as it's coming from a library. The issue I encounter is that when trying to access a property from myObject, TypeScri ...

"Angluar4 is throwing an error: it's unable to read the property 'iname' of

This is the code snippet from item.ts file:- export interface item{ $key?:string; available?:boolean; countable?:boolean; iname?:string; price?:string; desc?:string; image?:string; } The items component item.componenet.ts looks like this:- import { Com ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Encountering issues when attempting to set up graphqlExpress due to type

This is my first experience using GraphQL with Express. I have created a schema: import { makeExecutableSchema } from "graphql-tools"; import { interfaces } from "inversify"; const schema = ` type Feature { id: Int! name: String ...