Ionic 离子-石英多行插入

uqdfh47h  于 2022-12-09  发布在  Ionic
关注(0)|答案(2)|浏览(127)

对不起,基本的问题,但我正在努力了解哪一种是最好的方法来做到这一点。我是新的承诺和Angular /typescript/离子/javascript。
我有一个数组,我想在SQLlite表中为数组的每个元素插入一行。

-—————————————————-
编辑我的代码现在看起来像这样,它有点工作,但不知道是否有一个更好的方法(当然)

for(var a=0; a<this.myarray.length; a++){

  this.insertquery(this.myarray[a].parameter1,this.myarray[a].parameter2);

}
insertquery(value1,value2){

   this.databaseObj.executeSql('INSERT INTO mytable(field1, field2) VALUES ("'+value1+'","'+value2+'")',[])
.then(() => {
    alert('Row Inserted!');
})
.catch(e => {
    alert('error ' + JSON.stringify(e))
});
}

-—————————————————————————————————————————-

现在我的代码看起来是这样的
第一次
除了它不工作,因为我不知道是什么原因:)我敢肯定,这是不正确的,从“承诺”的Angular 来看,必须有一个更好的方法来做到这一点。
你对如何实现这一点有什么提示吗?
谢谢你!

kkih6yb8

kkih6yb81#

Here is a example how to add data to sqlite:
use the following command to insert: INSERT OR IGNORE INTO Table

const readline = require('readline');
    const fs = require('fs');
    const sqlite3 = require('sqlite3').verbose();

    let db;

    // database is not existing
        console.log('open database and create table');
        db = new sqlite3.Database('./event.db',() => {
          db.run('CREATE TABLE logTable(logfile TEXT,logdate TEXT,referto TEXT, area TEXT,status TEXT,action TEXT)',() => {
    var res = ['mylog.txt','03.10.2018','m1','Area1','ok','Load']
   // map fields to entry
      entryDate = '-';
      entry.logfile = res[0];
      entry.logdate = res[1];

      entry.action = res[5]; 
      entry.area = res[2];
      entry.referto = res[3];
      entry.status = res[4];

    db.run("INSERT OR IGNORE INTO logTable (logfile, logdate, referto, area, status, action) VALUES (?,?,?,?,?,?)",
     [entry["logfile"], entry["logdate"], entry["referto"], entry["area"], entry["status"], entry["action"]], function(err) {
      if (err) {
        return console.log(err.message);
      } else {
          db.close();
      }
      // get the last insert id
      console.log(`A row has been inserted with rowid ${this.lastID}`);
          });

see also here

zzoitvuj

zzoitvuj2#

我也遇到过类似的异步问题,最后我做了一个SELECT插入,这个过程只做了一个插入语句。

/*
    "params" its my JSON array, you could send just a simple array or 2d matrix
*/
CreateMany(storage: SQLiteObject, tableName: string, params: any[]) {
    // Get keys from the first JSON in array
    const keys = Object.keys(params[0]).filter(key => params[0][key].constructor != Object && !Array.isArray(params[0][key]));
    
    // Get SELECT UNION string
    let selectInsert: string = params.map(param => Object.values(param)).join(' union all SELECT ');

    // Build my query
    const query: string = `
        INSERT INTO ${tableName} (${keys.join()}) 
        SELECT * FROM (
            SELECT ${selectInsert}
        );
    `;

    return storage.executeSql(query, []);
}

相关问题