node.js mysql push callback

时间:2014-11-08 14:37:14

标签: mysql node.js

   mysql.query('SELECT accountID,deviceID FROM EventData WHERE accountID = "'
       + acc
       + '" AND deviceID = "'
       + deviceID
       + '"  ORDER BY timestamp DESC LIMIT 1 ',
           function(err,rows,fields) {                   
               if (rows.length > 0) {                 
                   var accountID = rows[0].accountID;
                   var deviceID = rows[0].deviceID;
                   var re2 = ({
                       title: deviceID,                    
                   });                      
                   console.log(re2)
                   console.log("aaa")     
           }
    );

上面的代码产生以下输出:

   [{ title: 'dev1'}]
   aaa
   [{ title: 'dev2'}]
   aaa

但我希望看到以下内容:

   [{ title: 'dev1'},
   { title: 'dev2'}]
   aaa

我做错了什么?

1 个答案:

答案 0 :(得分:1)

你甚至没有遍历行,你只是将第一个标题添加到re2。

此代码应该有效:

mysql.query('SELECT accountID,deviceID FROM EventData WHERE accountID = ? AND deviceID = ? ORDER BY timestamp DESC LIMIT 1', [acc, deviceID],
       function(err,rows,fields) {
           if (rows.length > 0) { 
               var re2 = [ ];                    
               for (var i = 0; i < rows.length; i++) {
                   re2.push({ title: rows[i].deviceID });
               }                    
               console.log(re2);
               console.log("aaa")  ;
           }   
       }
);

请注意,我使用占位符传递参数,而不是将它们显式连接到字符串。