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)原文地址 https://www.mgenware.com/blog/?p=2924&utm_source=tuicool&utm_medium=referral
本文测试环境: Node.js 4.2.2, node-mysql 2.9.0
使用node-mysql遇到Cannot enqueue Handshake after already enqueuing a Hand shake
。这个错误提示意思是某个数据库连接已经执行了,不能进行多次连接了。遇到此类情况,首先看下代码是否出现了同一个数据库连接多次调用connect
方法的情况,这种明显的错误排除后,看看是否在调用connect
前发生了隐式的连接操作,比如在未连接时直接调用query
做查询会间接去connect
,如下代码,createConnection
后直接调用query
也会触发连接:
var mysql = require('mysql');mysql.createConnection({ ...}).query('...', (err, res) => { if (err) { // 处理错误 } // 隐式连接,没有连接错误的话,数据会正常返回});
当然,也可以直接去掉显式的connect
调用,任由query
去做隐式连接,也不会出现上述错误,不过如果这样的话,强烈建议使用Pool,这样数据库连接可以最大化的实现复用和管理,和createConnection
返回的连接一样,Pool可以通过getConnection
返回一个连接,也可以直接用query
去自动复用或创建一个连接。不过如果使用pool.getConnection
的话,记得用完连接后调用connection.release
把连接返回给Pool。这两种方式多数情况下是等价的,除非查询包含多个语句,可以参考这个链接:.