Nodejs using MySQL connection pool, wire break reconnection

Source: Internet
Author: User
Tags mysql connection pool

Two ways of solving
1. You can configure MySQL connection pool

var mysql = require(‘mysql‘);var pool = mysql.createPool({    host: ‘localhost‘,    user: ‘nodejs‘,    password: ‘nodejs‘,    database: ‘nodejs‘,    port: 3306});var selectSQL = ‘select * from t_user limit 10‘;pool.getConnection(function (err, conn) {    if (err) console.log("POOL ==> " + err);    conn.query(selectSQL,function(err,rows){        if (err) console.log(err);        console.log("SELECT ==> ");        for (var i in rows) {            console.log(rows[i]);        }        conn.release();    });});

2, you can use the disconnection method to solve

var mysql = require(‘mysql‘);var conn;function handleError () {    conn = mysql.createConnection({        host: ‘localhost‘,        user: ‘nodejs‘,        password: ‘nodejs‘,        database: ‘nodejs‘,        port: 3306    });    //连接错误,2秒重试    conn.connect(function (err) {        if (err) {            console.log(‘error when connecting to db:‘, err);            setTimeout(handleError , 2000);        }    });    conn.on(‘error‘, function (err) {        console.log(‘db error‘, err);        // 如果是连接断开,自动重新连接        if (err.code === ‘PROTOCOL_CONNECTION_LOST‘) {            handleError();        } else {            throw err;        }    });}handleError();

Nodejs using MySQL connection pool, wire break reconnection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.