2014-10-15 2 views
0

나는 병합 콜백 기능/MySQL의 쿼리 문제가 :를 사용하여 콜백 MySQL의 기능

require('getmac').getMac(function(err, macAddress){ 
    if (err){ throw err; } 
    console.log(macAddress);  
}); 

모듈 :

https://github.com/felixge/node-mysql/

var mysql  = require('mysql'); 
var connection = mysql.createConnection({ 
    host : '100.100.100.100', 
    user : 'userX', 
    password: 'passwordX' 
}); 

connection.connect(); 
connection.query('use db1'); 
connection.query("SELECT nick FROM users WHERE id=1", function(err, rows, fields) { 

    if(rows.length!=0){ 
     //here "UPDATE users SET mac = "+macAddress+" WHERE id = 1;" 
    } 

    //here "SELECT COUNT(*) as Counter FROM users WHERE id = 1;" 
    //if(Counter>1){console.log('doubled mac'); 
}); 

내가 함수에서 변수 macAdress이

https://github.com/bevry/getmac

+1

그래서 문제가 무엇 : 주요 기능

하나는 당신이 같이 할 필요가 무엇을 읽을 수있는 코드에 비동기 작업을 결합의 waterfall입니까? –

+1

나는 당신이 묻는 것에 대해 분명하지 않다. 조금 더 자세히 설명 할 수 있니? –

+1

node-mysql에주의하십시오 - 메모리 누수, 메모리 누수, ..., 각 쿼리 후에 연결을 닫아야합니다. –

답변

0

async 모듈을 살펴보면 비동기 프로그래밍에 큰 도움이됩니다.

var mysql  = require('mysql'); 
var async  = require('async'); 
var connection = mysql.createConnection({ 
     host : '100.100.100.100', 
     user : 'userX', 
     password: 'passwordX' 
    }); 
connection.connect(); 
connection.query('use db1'); 
var macAddress; 
async.waterfall([ 
    function(next){ 
     require('getmac').getMac(next); 
    }, 
    function(ma, next){ 
     macAddress=ma; // store it globaly for further usage 
     connection.query("SELECT nick FROM users WHERE id=1", next); 
    }, 
    function(rows, fields, next){ 
     if(rows.length!=0){ 
      connection.query("UPDATE users SET mac = "+macAddress+" WHERE id = 1", next); 
     } else { 
      next(new Error("No Users found")); // do this if you want to stop here, else just call next(null); to proceed with the next function 
     } 
    }, 
    function(res, next) { // im not sure what args u get in return from the update sql query, you need to replace res with them 
     connection.query("SELECT COUNT(*) as Counter FROM users WHERE id = 1", next); 
    } 
], function (err, result) { // should probably be err, rows, fields 
    if (err) console.log("Got Error:", err); 
    console.log("Got Result:", result); 
});