Ошибка при вставке данных в таблицу в базе данных SQLite ioni c 4 - PullRequest
0 голосов
/ 08 апреля 2020

Я новичок в IONI C.

Я хочу сохранить данные в приложении.

Я устанавливаю плагин для базы данных SQLite:
ioni c Плагин Cordova Добавить Cordova-sqlite-Storage
npm install @ ioni c -native / sqlite

Он успешно создал базу данных и таблицу.
Но когда я вставляю строку, это вызывает синтаксическую ошибку.

Когда я пытаюсь вставить строку в таблицу, она показывает ошибку.

Я создал служебный файл для базы данных.

Это дает мне некоторую синтаксическую ошибку.

database.service.ts

export class DatabaseService {

  databaseObj: SQLiteObject;
  readonly database_name: string = "knowledgeup.db";
  readonly table_name: string = "scotetable";

  // name_model: string = "";
  categoryId: string = "";
  categoryName: string = "";
  attemptedQue: string = "";
  trueQue: string = "";
  wrongQue: string = "";
  score: string = "";
  lastQueId: string = "";

  row_data: any = [];

  // Handle Update Row Operation
  updateActive: boolean;
  to_update_item: any;

  constructor(private platform: Platform,
    private sqlite: SQLite) {
    this.platform.ready().then(() => {
      this.createDB();
    }).catch(error => {
      console.log(error);
    })
  }

  // Create DB if not there
  createDB() {
    this.sqlite.create({
      name: this.database_name,
      location: 'default'
    }).then((db: SQLiteObject) => {
        this.databaseObj = db;
        this.createTable();
        alert('Database Created!');
      })
      .catch(e => {
        alert("error " + JSON.stringify(e))
      });
  }

  // Create table
  createTable() {
    this.databaseObj.executeSql(`
    CREATE TABLE IF NOT EXISTS ${this.table_name}  (pid INTEGER PRIMARY KEY, categoryId varchar(255), categoryName varchar(255), attemptedQue varchar(255), trueQue varchar(255), wrongQue varchar(255), score varchar(255), lastQueId varchar(255))
    `, [])
      .then(() => {
        alert('Table Created!');
      })
      .catch(e => {
        alert("error " + JSON.stringify(e))
      });
  }

  //Inset row in the table
  insertRow(catId,catName,attempQue,correctQue,wrongQue,totalScore,lastQueId ) {
    // Value should not be empty
    if (!catId) {
      alert("Enter categoryId");
      return;
    }

    this.databaseObj.executeSql(`
      INSERT INTO ${this.table_name} (categoryId) VALUES ('${catId}'), (categoryName) VALUES ('${catName}'), (attemptedQue) VALUES ('${attempQue}'), (trueQue) VALUES ('${correctQue}'), (wrongQue) VALUES ('${wrongQue}'), (score) VALUES ('${totalScore}'), (lastQueId) VALUES ('${lastQueId}')
    `, [])
      .then(() => {
        alert('Row Inserted!');
        this.getRows();
      })
      .catch(e => {
        alert("error " + JSON.stringify(e))
      });
  }

  // Retrieve rows from table
  getRows() {
    this.databaseObj.executeSql(`
    SELECT * FROM ${this.table_name}
    `
      , [])
      .then((res) => {
        this.row_data = [];
        if (res.rows.length > 0) {
          for (var i = 0; i < res.rows.length; i++) {
            this.row_data.push(res.rows.item(i));
          }
        }
      })
      .catch(e => {
        alert("error " + JSON.stringify(e))
      });
  }

  // Delete single row 
  deleteRow(item) {
    this.databaseObj.executeSql(`
      DELETE FROM ${this.table_name} WHERE pid = ${item.pid}
    `
      , [])
      .then((res) => {
        alert("Row Deleted!");
        this.getRows();
      })
      .catch(e => {
        alert("error " + JSON.stringify(e))
      });
  }

  // Enable update mode and keep row data in a variable
  enableUpdate(item) {
    this.updateActive = true;
    this.to_update_item = item;
    this.categoryId = item.categoryId;
    this.categoryName = item.categoryName;
    this.attemptedQue = item.attemptedQue;
    this.trueQue = item.trueQue;
    this.wrongQue = item.wrongQue;
    this.score = item.score;
    this.lastQueId = item.lastQueId;
  }

  // Update row with saved row id
  updateRow() {
    this.databaseObj.executeSql(`
      UPDATE ${this.table_name}
      SET categoryId = '${this.categoryId}', 
      categoryName = '${this.categoryName}',
      attemptedQue = '${this.attemptedQue}',
      trueQue = '${this.trueQue}',
      wrongQue = '${this.wrongQue}',
      score = '${this.score}',
      lastQueId = '${this.lastQueId}'
      WHERE pid = ${this.to_update_item.pid}
    `, [])
      .then(() => {
        alert('Row Updated!');
        this.updateActive = false;
        this.getRows();
      })
      .catch(e => {
        alert("error " + JSON.stringify(e))
      });
  }
}

quiz.page.ts

constructor(public databaseService: DatabaseService) { }

 btnExitClick() {
 this.databaseService.insertRow(this.categoryId,this.title,this.sessionAttemptedQue,this.sessionTrueQue,this.sessionFalseQue,this.sessionUserScore,this.questionData.questionId);
}

enter image description here

...