报错信息
events.js:292
throw er;
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
--------------------
at Protocol._enqueue (******\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (******\node_modules\mysql\lib\Connection.js:198:25)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (******\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (events.js:315:20)
at Protocol._delegateError (******\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Query.<anonymous> (******\node_modules\mysql\lib\protocol\Protocol.js:153:12)
at Query.emit (events.js:315:20)
at Query.Sequence.end (******\node_modules\mysql\lib\protocol\sequences\Sequence.js:78:12)
at Protocol.handleNetworkError (******\node_modules\mysql\lib\protocol\Protocol.js:369:14)
at Connection._handleNetworkError (******\node_modules\mysql\lib\Connection.js:418:18)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
error Command failed with exit code 1.
info Visit https:
封装查询方法
const option = {
host: ‘**********’,
port: '******',
user: process.env.npm_lifecycle_event==='build'?'xxxx':'xxxx',
password: '********',
database: '****',
connectionLimit: 10
}
const mysql = require('mysql')
const pool = mysql.createPool(option)
function query(res, sql, params = []){
return new Promise((resolve, reject) => {
pool.getConnection((cerr, con) => {
if(cerr) {
console.log('和mysql数据库建立连接失败');
res.json({data: false, msg: '发生未知错误,请稍后再试。'})
reject(cerr)
} else {
con.query(mysql.format(sql, params),(err, row) => {
con.release();
if(err) {
if(err.code === 'ER_DUP_ENTRY') {
res.json({data: false, msg: '数据重复,添加失败。'})
} else if(err.code === 'ER_NO_DEFAULT_FOR_FIELD') {
res.json({data: false, msg: '缺少字段,添加失败。'})
} else {
res.status(500).json({data: false, msg: '发生未知错误,请稍后再试。'})
}
reject(err)
} else {
resolve(row)
}
})
}
})
})
}
module.exports = query