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

Electron连接MariaDB数据库超时失败,请求排查解决

解决Electron连接MariaDB超时问题

错误分析

你遇到的SqlError: retrieve connection from pool timeout错误,说明Electron无法建立到Ubuntu上MariaDB的网络连接,连接池无法获取可用连接(active=0 idle=0)。结合你本地能正常访问数据库的情况,问题大概率出在数据库远程权限、防火墙或网络配置上,同时代码也有可优化的点。

解决方案

1. 给MariaDB用户授权远程访问权限

默认情况下MariaDB用户只允许本地(localhost)访问,需要修改权限允许Windows主机连接:

  • 登录Ubuntu本地MariaDB:mysql -u root -p
  • 执行授权命令(替换你的用户名、你的密码,%允许所有IP连接,也可以指定Windows主机的具体IP更安全):
    GRANT ALL PRIVILEGES ON 你的数据库名.* TO '你的用户名'@'%' IDENTIFIED BY '你的密码';
    FLUSH PRIVILEGES;
    
  • 退出MariaDB:exit;

2. 开放Ubuntu防火墙的3306端口

Ubuntu默认的ufw防火墙可能拦截了3306端口(MariaDB默认端口),执行以下命令开放:

sudo ufw allow 3306/tcp
sudo ufw reload

如果想更严格,只允许你的Windows主机IP访问:

sudo ufw allow from 你的Windows_IP to any port 3306
sudo ufw reload

3. 修改MariaDB绑定地址

默认MariaDB只绑定本地回环地址(127.0.0.1),需要改成允许监听所有网卡:

  • 编辑MariaDB配置文件:sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf
  • 找到bind-address行,修改为:
    bind-address = 0.0.0.0
    
    或者指定Ubuntu的局域网IP(比如192.168.1.100)
  • 重启MariaDB服务:sudo systemctl restart mariadb

4. 修正Electron代码中的连接配置

你的代码存在两个问题:

  • 每次提交表单都创建新的连接池,资源浪费且可能导致连接异常
  • 连接池配置缺少database参数,且timeout设置不合理(5毫秒太短,且应该用connectTimeout控制连接超时)

优化后的代码:

// 把连接池创建放在事件监听外面,全局复用
const json = JSON.stringify(env);
const dbdata = JSON.parse(json);

// 全局创建连接池
const pool = mariadb.createPool({
    host: dbdata.DB_HOST, // 这里填Ubuntu的局域网IP,不要用localhost
    user: dbdata.DB_USER,
    password: dbdata.DB_PASSWORD,
    database: '你的数据库名称', // 必须指定要连接的数据库
    connectTimeout: 10000, // 连接超时设为10秒
    acquireTimeout: 10000, // 获取连接超时设为10秒
    idleTimeout: 30000,
    connectionLimit: 10
});

document.getElementById('loginForm').addEventListener('submit',function(event){
    event.preventDefault();

    const username = document.getElementById('usr').value;
    const password = document.getElementById('pwd').value;

    let hash = crypto.createHash('sha256');
    hash.update(password);
    
    pool.getConnection()
        .then(conn => {
            return conn.query('SELECT * FROM accountData WHERE Username = ? AND Password = ?', [username, hash.digest('hex')])
                   .finally(() => conn.release()); // 用完连接要释放回池
        })
        .then(rows => {
            if(rows.length > 0){
                alert("ok");
            }
            else{
                alert("bad");
            }
        })
        .catch(err => {
            console.log(err);
        });
})

5. 测试网络连通性

在Windows主机上执行以下命令,确认网络能通:

  • ping Ubuntu的IP:ping 192.168.1.100(替换为你的Ubuntu IP)
  • 测试3306端口:telnet 192.168.1.100 3306 或者用PowerShell:Test-NetConnection 192.168.1.100 -Port 3306

如果端口不通,回到步骤2和3检查防火墙和MariaDB绑定配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 10:44:58