mysqljs / mysql

A pure node.js JavaScript Client implementing the MySQL protocol.
MIT License
18.28k stars 2.52k forks source link

Initial successfull connecction callback for connecton pooling (DOCS update) #2513

Closed shivarajnaidu closed 3 years ago

shivarajnaidu commented 3 years ago

Hi

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
});

connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

  console.log('connected as id ' + connection.threadId);
});

with the above code for connections creation we can print successfully connected message initially to indicate the the db is connected

How to do the same when we create a new pool and want to know that the server successfully connected before executing any queries ..

var mysql = require('mysql');
var pool  = mysql.createPool(...);

how to print the initial connected to db message with this...

If there is a way please add it to docs, it will be very useful indicate the successful db connection.

Thank You !

dougwilson commented 3 years ago

https://github.com/mysqljs/mysql#connection


pool.on('connection', function(connection){
  console.log('connected as id ' + connection.threadId);
});
shivarajnaidu commented 3 years ago

Thanks for the response @dougwilson . I have one more query..

Will this event emited immediately when I start the application , I mena when I create the new pool ?

dougwilson commented 3 years ago

The pool will emit a connection event when a new connection is made within the pool. Creating the pool won't create a connection until you ask it for a connection.

shivarajnaidu commented 3 years ago

So for the first time when I start my node server how to know whether my ORM successfully connected to the dB server ..

Do I need to execute some query to know the dB connection successful (when i use pooling)?

(Just want to ensure that the dB part is working when i start the Web server )

dougwilson commented 3 years ago

You could execute a query, or even just call getConnection and then release it back if you want. Usually checking that on start is a bit of an antipattern, though, as it can stop connecting right at any point after your app started.

shivarajnaidu commented 3 years ago

Yeah.. you are right we can do getconnection to test the successful connection to db;

The reason behind this is i want to ensure that the db connection from the application is working as expected when i deploy an instance @dougwilson So that can i avoid initial clear failure of connection right.

Anyways thanks for pointing me the way to achieve what i want with pooling.