Check mysql connection in sequelize

早过忘川 提交于 2019-12-04 22:27:09

As of latest version of Sequelize (i.e. 3.3.2), authenticate can be used to check the connection:

var sequelize = new Sequelize("db", "user", "pass");

sequelize.authenticate().then(function(errors) { console.log(errors) });

authenticate simply runs SELECT 1+1 AS result query to check the db connection.

UPDATE:

Errors by the newest API need to be handled in catch:

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

You won't see errors, like password authentication errors, in .then.

From the sequelize documentation here:

You can use the .authenticate() function like this to test the connection.

sequelize
  .authenticate()
  .then(function(err) {
    console.log('Connection has been established successfully.');
  })
  .catch(function (err) {
    console.log('Unable to connect to the database:', err);
  });

Please check "wait_timeout" system variable if its been reset to some trivial value

I use the following code to wait for the db engine to start:

function sleep(ms) {

    return new Promise(function(resolve) {

        setTimeout(resolve, ms);
    });
}

for (;;) {

    try {

        await db.authenticate();
        break;
    } catch(ex) {

        await sleep(1000);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!