sqlite3 - 按键数组插入多行

时间:2017-11-05 12:33:06

标签: javascript sqlite

我有三个表格(personlanguagepersonSpeaksLanguage),我希望按照给定的ID insertOrUpdate链接表(personSpeaksLanguagepersonId)和键数组(languageIds)。 如何存档?

示例:

person
| id | name    |
|  1 | 'Maria' |
|  2 | 'Jim'   |
|  4 | 'John'  |

language
| id | name      |
|  1 | 'english' |
|  2 | 'spanish' |
|  4 | 'japanse' |

personSpeaksLanguage
| personId | languageId | deleted |
|    1     |     2      |    0    |
|    4     |     2      |    1    |
|    4     |     3      |    0    |
|    2     |     1      |    1    |


Example vars: 
  database='./database.db'  
  table='personSpeaksLanguage' 
  personId=2 
  languageIds=[1,2,4]

目的是为personSpeaksLanguage实现价值(2,2)和(2,4)的添加。由于(2,1)已经在表格中。但之前得到了软删除,它应updatedeleted = 0。这是我的可怜尝试,没有update

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

export default function insertOrUpdateMultiple(database, table, personId, languageIds) {
  return new Promise((resolve, reject) => {
    const db = new sqlite3.Database(database);
    let i = 0;
    while (i < languageIds.length) {
      db.run(`INSERT INTO ${table} (id, name) VALUES (${personId}, ${languageIds[i]})`, values, (err) => {
        if (err) reject(err);
      }, (err) => {
        if (err) {
          reject(err);
        } else {
          i += 1;
        }
      });
    }
  });
}

1 个答案:

答案 0 :(得分:0)

this的帮助下,我得到了:

INSERT INTO mytable (col1, col2, col3) VALUES
    (1, 2, "abc"),
    (2, 4, "xyz"),
    (3, 5, "aaa"),
    (4, 7, "bbb");

我将languageIds合并到了对((${personId}, ${languageIds[i]})并加入了它们。

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

export default function insertOrUpdateMultiple(database, personId, languageIds, values) {
  const vals = [];
  for (let i = 0; i < languageIds.length; i += 1) {
    vals.push(`(${personId}, ${languageIds[i]})`);
  }
  const valStr = vals.join(', ');

  return new Promise((resolve, reject) => {
    const db = new sqlite3.Database(database);
    db.run(`INSERT INTO ${table} (personId, languageId) VALUES ${valStr}`, (err) => {
      if (err) reject(err);
    }, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}