首页 > 解决方案 > 尝试使用 Node.js 和 mysql javascript 客户端连接到 MySQL 数据库

问题描述

所以我一直在尝试从我的电子应用程序连接到 MySQL 数据库:

    <script>
    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host     : '*********',
        user     : '******',
        password : '******',
        port     : '******',
        debug    : 'true'
    });
    console.log('trying to connect to DB')
    connection.connect(function(err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            return;
        }    
        console.log('connected as id ' + connection.threadId);
        });
    connection.end()
</script>

我的代码卡在 connection.connect 上,大约 1 分钟后它给了我:

    error connecting: Error: read ECONNRESET
      at exports._errnoException (util.js:1024:11)
      at TCP.onread (net.js:610:25)

我不知道该怎么办,有人有什么想法吗?

标签: javascriptmysqlnode.jsdatabaseelectron

解决方案


很可能您的局域网上的 mssql 实例未配置为允许连接到除本地计算机(即安装了 mssql 的计算机)之外的任何设备。

要允许来自 LAN 的连接,您需要编辑以下内容:

编辑 my.conf 并在 [mysqld] 部分中找到 bind-address 参数,这可能会设置为 localhost 或 127.0.0.1,您可以将其更改为要连接到数据库的机器的 ip,或者使用通配符并允许您的整个本地范围,例如 192.168.0.* 或 0.0.0.0

您将需要授予对您尝试连接的数据库的访问权限

GRANT ALL ON <local database name>.* TO <user>@<iptryingtoconnectfrom> IDENTIFIED BY '<database user password>';

重新启动 mysql 服务,您应该一切顺利。


推荐阅读