【问题标题】:Queries being run twice on sql.js在 sql.js 上运行两次查询
【发布时间】:2018-10-24 05:34:53
【问题描述】:

我在我的项目中使用带有 sql.js 的 SQLite,但我的实现遇到了一些问题。似乎查询在数据库上运行了两次,因为对于 INSERT 语句,我在数据库中获得了 2 条记录。

我这样做的方式是创建 SQL,然后将其传递给此方法(opts 变量包含要放入数据库的所有数据):

prepareStatementAndCompileResults(db, sql, opts){
   const stmt = db.prepare(sql); 
   const result = stmt.getAsObject(opts);
   var rows = [];
   if(!this.isEmpty(result)){ // isEmpty is a simple method that checks for empty objects
      rows.push(result);
   } 
   while(stmt.step()) {
      var row = stmt.getAsObject();
      rows.push(row); 
   }
   this.saveToFile(db);
   stmt.free();
   return rows; 
},

这是一个正在运行两次的示例 SQL INSERT

INSERT OR IGNORE INTO tag_event (tag_id, event_id, unique_string) 
  VALUES (:tag_id,:event_id, :unique);

下面是这个查询的 opts 变量的样子:

var opts = {
   [':tag_id']: 1,
   [':event_id']:1, 
   [':unique']: '1-1'
}

【问题讨论】:

    标签: node.js sqlite sql.js


    【解决方案1】:

    因为您要将它推入第 2 行。

    // if not empty will add to row
    if(!this.isEmpty(result)){ // isEmpty is a simple method that checks for empty objects
        rows.push(result);
    } 
    
    
    // not sure what step() does but I'm assuming this will also run
    while(stmt.step()) {
          var row = stmt.getAsObject();
          rows.push(row); 
    }
    

    在保存前的while循环之后使用调试器或仅console.log(rows)进行验证

    【讨论】:

      【解决方案2】:

      所以,我需要做的是在获取变量之前将变量绑定到准备好的语句,而不是通过getAsObject 绑定它们。这样效率更高。我在本地测试中的 API 响应时间从 785 毫秒变为 14.5 毫秒

      prepareStatementAndCompileResults(db, sql, opts){
          const rows = [];
          const stmt = db.prepare(sql); 
          stmt.bind(opts);
      
          while(stmt.step()) {
             var row = stmt.getAsObject();
             rows.push(row); 
          }
          this.saveToFile(db);
          stmt.free();
          return rows; 
      },
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-07
        • 2011-02-14
        • 2014-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多