2013-10-24 41 views
1

當我關閉在數據庫連接的Node.js我收到此錯誤如何關閉node.js中的數據庫連接?

Cannot enqueue Query after invoking quit

這裏是我的代碼

socket.on('adminConnect', function (email) { 
    connection = mysql.createConnection(db_config); // db_config has all details of database 
    connection.connect(); // no problem in connection 
    connection.query("SELECT id FROM user WHERE email = '" + email + "' ", function (err, results, fields) { 
     if (err) throw err; 
     if (results[0]) { 
      // Some code 
      connection.end(); // its giving error "Cannot enqueue Query after invoking quit." 
     } else { 
      console.log("no id"); 
     } 
    }); 
}); 
+5

通常情況下,你不希望創建爲每個reques一個新的連接噸。保持連接以獲得更多額外的查詢。 – Zeta

+0

好吧,我會做到這一點。但我的問題是在哪裏結束連接? – Vardan

+2

@用戶您的觀點不是。爲什麼要關閉可以重用的連接?連接很便宜,但打開它們需要一次或三次。 –

回答

1

一般情況下,重用/關閉所有的時間連接,而不是打開。

要回答你的問題,這是多麼:

connection.end(); 

嘗試把回調線外,因爲所有的查詢必須結束連接之前完成,所以你是安全的這樣的:

然後
connection.query(.......); 
connection.end(); 

您的代碼將是:

socket.on('adminConnect', function (email) { 
    connection = mysql.createConnection(db_config); // db_config has all details of database 
    connection.connect(); // no problem in connection 
    connection.query("SELECT id FROM user WHERE email = '" + email + "' ", function (err, results, fields) { 
     if (err) throw err; 
     if (results[0]) { 
      // Some code 
     } else { 
      console.log("no id"); 
     } 
    }); 
    connection.end(); 
}); 
+0

如果我不必再使用連接,這個答案是正確的。如果我不得不重新使用它,它不需要關閉。感謝randunel。 – Vardan

+2

在調用'connection.end'之前,你並沒有等待'connection.query'完成。它應該在'connection.query'回調中調用。 – robertklep

+2

@robertklep要是你當初作出錯誤的假設前瀏覽文檔的時候,你會注意到,你可以叫'.END()'觸發回調之前,因爲'關閉連接使用結束(完成),這確保在將退出的數據包發送到mysql服務器之前執行所有剩餘的查詢。 - 引用node-mysql文檔。有一個類似代碼的文檔中有一個例子。 https://github.com/felixge/node-mysql#introduction。關於重新使用連接,請閱讀我的答案中的第一段;) – randunel