sequelize连接mysql,检查sequelize中的mysql连接

本文介绍了一种使用Sequelize库检查MySQL数据库是否正常运行的方法。当MySQL服务未启动时,通常期望能立即收到错误反馈而不是等待超时。文章提供了一个简单示例并展示了如何通过Sequelize的authenticate方法来实现这一需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have a very simple program in where I create a Sequelize instance and then I perform a raw query on a mysql database.

The case is that when MySql is up and running there is no problem, I can perform the query with no problems.

But when MySql is not running then the query doesn't emmit any error until the query timeout has reached and then it emmits a ETIMEOUT error. But that's not really what's happening. I expect the query to emit ENOTFOUND error or something like that if mysql is not running so I can manage the error and perform different actions if Mysql has gone down or Mysql is very busy and has a very large response time.

What shoul'd I do to check if Mysql is up and running without having to wait the timeout exception.

sequelize = new Sequelize(db_name, db_user, db_pass, opts);

sequelize.query('SELECT * FROM some_table').success(function(result) {

console.log(result);

}).error(function(err) {

console.log(err);

});

解决方案

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);

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值