MySQL之使用连接池

NodeJS

2021年11月03日 16:09:211568

报错信息

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

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://yarnpkg.com/en/docs/cli/run for documentation about this command.

封装查询方法

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
赞 2
收藏
分享

本作品系 原创,作者:x先生

原文链接:https://shiniest.cn/blog/article/138

文本版权:文本版权归作者所有

转载需著名并注明出处(禁止商业使用)

评论和回复

0/500
    没有更多啦~
    怎么一条数据都没有呢?
简介
之前MySQL没有使用连接池,而是使用的直连的方式,后来出现了几次莫名其妙的报错(不是Timeout),把我整不会了,但报错的诸多信息始终都是指向MySQL封装方法的,所以。。。
目录

D&D By x先生 With