如何检查mysql连接是否有效

问题描述 投票:0回答:1

我用的是node,用的是'mysql2'模块,如何检查配置设置是否正确,连接数据库是否正确?

这些是我的连接设置,但是我想在做任何查询之前检查数据库连接是否有效,比如允许用户登录。

const mysql = require('mysql2');

const conn = mysql.createPool({
    host: 'hostname',
    port: port,
    database: 'db',
    user: 'root',
    password: 'password',
    dateStrings: 'date'
});

const pool = conn.promise();

module.exports = pool;

我添加了这段代码(在module.exports行之前)来抛出一个错误,但是有没有更好的方法?错误代码-3008与'ENOTFOUND'代码有关,当主机名不正确,连接失败时,我收到的就是这个代码。

pool.execute('SELECT * FROM table LIMIT 1')
.catch(err => {
    if (err.errno === -3008) {
        throw new Error('Can\'t connect to database please check connection settings.');
    }
});
node.js mysql2
1个回答
0
投票

你是否可以通过命令行连接你的mysql?

mysql -h localhost -u myname -ppassword mydb

另外,为了在执行查询前测试连接,我建议你使用以下方法 .getConnection

© www.soinside.com 2019 - 2024. All rights reserved.