You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用mysql@2.18.1连接Azure MySQL时遇TypeError求助

解决Node.js连接Azure MySQL时的TypeError问题

你的错误是因为模块导入方式错误导致的。mysql@2.18.1模块的默认导出就是核心连接对象,不是包含mysql属性的命名导出,所以你用const { mysql } = require('mysql');解构出来的mysql是undefined,调用createConnection自然会抛出Cannot read properties of undefined错误。

修正后的代码

把导入语句改成默认导入即可:

const mysql = require('mysql');

var sqlConfig = {
    host        : '*****************',
    port        : 3306,
    user        : '*****',
    password    : '**********',
    database    : '*******'
};

var connection = mysql.createConnection(sqlConfig);

额外验证步骤

  1. 确保依赖安装正确,执行命令:
npm install mysql@2.18.1
  1. 可以添加连接测试逻辑,确认连接是否正常:
connection.connect((err) => {
    if (err) {
        console.error('连接失败:', err.stack);
        return;
    }
    console.log('已成功连接到数据库,连接ID:', connection.threadId);
});

注意事项

  • Azure MySQL的用户名格式必须是用户名@Azure服务器名,如果你的用户名没带服务器后缀,需要补充完整
  • 检查Azure MySQL的防火墙规则,确保你的Node.js运行环境IP被允许访问数据库

内容的提问来源于stack exchange,提问作者JBrittD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:17:04