node-mysql: connect時的」Cannot enqueue Handshake after already enqueuing a Hand shake」錯誤

events.js:160
      throw er; // Unhandled 'error' event
      ^


Error: Cannot enqueue Handshake after invoking quit.
    at Protocol._validateEnqueue (D:\bookstore\node_modules\mysql\lib\protocol\Protocol.js:202:16)
    at Protocol._enqueue (D:\bookstore\node_modules\mysql\lib\protocol\Protocol.js:135:13)
    at Protocol.handshake (D:\bookstore\node_modules\mysql\lib\protocol\Protocol.js:52:41)
    at Connection.connect (D:\bookstore\node_modules\mysql\lib\Connection.js:130:18)
    at D:\bookstore\build\dev-server.js:50:14
    at Layer.handle [as handle_request] (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\layer.js:95:5)
    at next (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\route.js:137:13)
    at Route.dispatch (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\layer.js:95:5)
    at D:\bookstore\node_modules\_express@4.15.3@express\lib\router\index.js:281:22
    at param (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\index.js:354:14)
    at param (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\index.js:365:14)
    at Function.process_params (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\index.js:410:3)
    at next (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\index.js:275:10)
    at Function.handle (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\index.js:174:3)
    at router (D:\bookstore\node_modules\_express@4.15.3@express\lib\router\index.js:47:12)
javascript


原文地址 https://www.mgenware.com/blog/?p=2924&utm_source=tuicool&utm_medium=referraljava


本文測試環境: Node.js 4.2.2, node-mysql 2.9.0node

使用node-mysql遇到Cannot enqueue Handshake after already enqueuing a Hand shake。這個錯誤提示意思是某個數據庫鏈接已經執行了,不能進行屢次鏈接了。遇到此類狀況,首先看下代碼是否出現了同一個數據庫鏈接屢次調用connect方法的狀況,這種明顯的錯誤排除後,看看是否在調用connect前發生了隱式的鏈接操做,好比在未鏈接時直接調用query作查詢會間接去connect,以下代碼,createConnection後直接調用query也會觸發鏈接:mysql

var mysql = require('mysql');
mysql.createConnection({...}).query('...', (err, res) => {
    if (err) {
        // 處理錯誤
    }
    // 隱式鏈接,沒有鏈接錯誤的話,數據會正常返回
});

固然,也能夠直接去掉顯式的connect調用,任由query去作隱式鏈接,也不會出現上述錯誤,不過若是這樣的話,強烈建議使用Pool,這樣數據庫鏈接能夠最大化的實現複用和管理,和createConnection返回的鏈接同樣,Pool能夠經過getConnection返回一個鏈接,也能夠直接用query去自動複用或建立一個鏈接。不過若是使用pool.getConnection的話,記得用完鏈接後調用connection.release把鏈接返回給Pool。這兩種方式多數狀況下是等價的,除非查詢包含多個語句,能夠參考這個連接:Difference between using getConnection() and using pool directly in node.js with node-mysql module?.sql

相關文章
相關標籤/搜索