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

Node.js中MySQL2用URI格式连接报Access denied错误的问题求助

Node.js + MySQL2 URI连接问题与解决方案

URI连接失败的原因及修复

1. 密码编码需覆盖完整内容

密码中的特殊字符要整体通过encodeURIComponent()编码,而非仅单独替换@。即便你已将@替换为%40,确保对整个密码编码能规避其他潜在特殊字符的干扰:

const encodedPassword = encodeURIComponent('My@Password');
const connection = mysql2.createConnection(
  `mysql://root:${encodedPassword}@localhost:3306/MyDB`
);

2. 连接协议存在差异

使用对象参数且未指定port时,mysql2默认通过Unix套接字连接本地MySQL;而URI中显式写3306端口会强制走TCP连接。如果你的root@localhost用户仅被授权通过套接字连接,就会触发权限错误。

  • 验证方式:在对象参数里添加port:3306,若同样报错,说明是MySQL权限配置问题,需修改权限允许root@localhost通过TCP连接。
  • 临时修复:去掉URI中的端口,让mysql2默认用套接字连接:
    const connection = mysql2.createConnection(
      'mysql://root:My%40Password@localhost/MyDB'
    );
    

生成正确URI的方法

mysql2没有内置直接生成URI的工具,但可以用Node.js内置的url模块从连接对象构建:

import mysql2 from 'mysql2';
import url from 'url';

const connectionConfig = {
  host: 'localhost',
  user: 'root',
  password: 'My@Password',
  database: 'MyDB',
};

// 构建编码后的URI
const connectionUri = url.format({
  protocol: 'mysql',
  username: connectionConfig.user,
  password: encodeURIComponent(connectionConfig.password),
  host: connectionConfig.host,
  pathname: `/${connectionConfig.database}`,
});

// 使用生成的URI建立连接
const connection = mysql2.createConnection(connectionUri);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 12:20:15