检查sequelize中的mysql连接 [英] Check mysql connection in sequelize
问题描述
我有一个非常简单的程序,在其中创建Sequelize实例,然后在mysql数据库上执行原始查询. 这种情况是,当MySql启动并运行时没有问题,我可以毫无问题地执行查询. 但是,当MySql没有运行时,查询不会发出任何错误,直到达到查询超时为止,然后发出ETIMEOUT错误.但这不是真的发生了什么.我希望查询会发出ENOTFOUND错误或类似的信息(如果mysql未运行),因此如果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);
});
这篇关于检查sequelize中的mysql连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!