SQLITE 3不写入表

时间:2019-02-18 18:00:50

标签: sqlite ecmascript-6

我正在尝试存储这样的对象数组。

   "id": "EExKKTC8IuL",
    "date": "2019-02-18T14:57:52.997Z",
    "timestamp": "1550500384",
    "title": "Financial Giant SBI Aims to Boost Ripple and Push XRP Ahead of Bitcoin in Crypto Market CapFinancial Giant SBI Aims to Boost Ripple and Push XRP Ahead of Bitcoin in Crypto Market Cap",
    "score": 6,
    "comparative": 0.18181818181818182

进入更好的sqlitev3表。我通常能够通过简单的id KEY自动增量来做到这一点。但是我试图将文章的ID保留在db中,以便它们不会重复。这是代码。

    try {

    const table = "coinna"
    const dbFile = "scraped"
    const dataDir = "./data/"
    const dbExt = ".db"

    const dbConn = db(`${dataDir}${dbFile}${dbExt}`);
    dbConn.prepare("PRAGMA journal_mode = WAL").run();
    dbConn
      .prepare(
        `CREATE TABLE IF NOT EXISTS [${table}] (id PRIMARY KEY, date DATETIME, timestamp INT, title VARCHAR, score DECIMAL, comparative INT)`
      )
      .run();

    const insertStmt = dbConn.prepare(
      `INSERT INTO [${table}] (date, timestamp, title, score, comparative) VALUES (?, ?, ?, ?, ?)`
    );
    dbConn.transaction(() => {
      parsedResults.forEach(
        ({ date, timestamp, title, score, comparative }) =>
          insertStmt.run(
            date, 
            timestamp, 
            title, 
            score, 
            comparative
          )
      );
    })
    console.log(`${parsedResults.length} added to ${table}`);
} 

      catch (e) {
         console.log(e.message);
       }

1 个答案:

答案 0 :(得分:0)

问题是我缺少();。

下面的答案。

   try {

    const table = "coinna"
    const dbFile = "scraped"
    const dataDir = "./data/"
    const dbExt = ".db"

    const dbConn = db(`${dataDir}${dbFile}${dbExt}`);
    dbConn.prepare("PRAGMA journal_mode = WAL").run();
    dbConn
      .prepare(
        `CREATE TABLE IF NOT EXISTS [${table}] (id PRIMARY KEY, date DATETIME, timestamp INT, title VARCHAR, score DECIMAL, comparative INT)`
      )
      .run();

    const insertStmt = dbConn.prepare(
      `INSERT INTO [${table}] (date, timestamp, title, score, comparative) VALUES (?, ?, ?, ?, ?)`
    );
    dbConn.transaction(() => {
      parsedResults.forEach(
        ({ date, timestamp, title, score, comparative }) =>
          insertStmt.run(
            date, 
            timestamp, 
            title, 
            score, 
            comparative
          )
      );
    })(); //here is where the (); needed to be.
    console.log(`${parsedResults.length} added to ${table}`);
} 

      catch (e) {
         console.log(e.message);
       }