Check mysql connection in sequelize(在 sequelize 中检查 mysql 连接)
问题描述
我有一个非常简单的程序,我在其中创建了一个 Sequelize 实例,然后对 mysql 数据库执行原始查询.情况是当MySql启动并运行没有问题时,我可以毫无问题地执行查询.但是当 MySql 没有运行时,查询不会发出任何错误,直到达到查询超时,然后它会发出 ETIMEOUT 错误.但事实并非如此.如果 mysql 未运行,我希望查询会发出 ENOTFOUND 错误或类似的错误,因此如果 Mysql 已关闭或 Mysql 非常忙并且响应时间非常长,我可以管理错误并执行不同的操作.我应该怎么做才能检查 Mysql 是否已启动并运行而无需等待超时异常.
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);
});
推荐答案
截至最新版本 Sequelize(即3.3.2),authenticate 可用于检查连接:
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 只需运行 SELECT 1+1 AS result 查询来检查数据库连接.
authenticate simply runs SELECT 1+1 AS result query to check the db connection.
更新:
最新 API 需要的错误在catch中处理:
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);
});
更新 2:
我没有对此进行测试,但唯一合乎逻辑的是,使用 async/await 可以达到相同的效果:
I haven't tested this, but its only logical that the same thing can be reached with async/await:
try {
await sequelize.authenticate()
} catch (err) {
console.error('Unable to connect to the database:', err)
}
这篇关于在 sequelize 中检查 mysql 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 sequelize 中检查 mysql 连接
基础教程推荐
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
