📜  nodejs mysql 连接池 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:19.197000             🧑  作者: Mango

代码示例1
var mysql = require('mysql');

// connect to the db
dbConnectionInfo = {
  host: "localhost",
  port: "3306",
  user: "root",
  password: "root",
  connectionLimit: 5, //mysql connection pool length
  database: "db_name"
};

//For mysql single connection
/* var dbconnection = mysql.createConnection(
        dbConnectionInfo
); 

 dbconnection.connect(function (err) {
    if (!err) {
        console.log("Database is connected ... nn");
    } else {
        console.log("Error connecting database ... nn");
    }
}); 

*/

//create mysql connection pool
var dbconnection = mysql.createPool(
  dbConnectionInfo
);

// Attempt to catch disconnects 
dbconnection.on('connection', function (connection) {
  console.log('DB Connection established');

  connection.on('error', function (err) {
    console.error(new Date(), 'MySQL error', err.code);
  });
  connection.on('close', function (err) {
    console.error(new Date(), 'MySQL close', err);
  });

});


module.exports = dbconnection;