问题描述
我有一个非常简单的程序,我在其中创建了一个 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 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!