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

Node/Express项目连接本地MySQL成功但无法执行INSERT插入操作求助

问题描述

我正在开发一个练习用的简单React & Node/Express应用,尝试通过index.js文件连接本地MySQL数据库,但最初始终无法成功建立连接。
我已确认所有依赖均已安装,为此已经排查了数小时。
目前我可以通过终端手动向对应的band_reviews表插入新记录,操作及返回结果如下:

mysql> INSERT INTO band_reviews (bandName, bandReview) VALUES ('Lofi','Really cool');
Query OK, 1 row affected (0.01 sec)

+----+-----------+-------------+
| id | bandName  | bandReview  |
+----+-----------+-------------+
|  1 | Coldfire  | Awesome     |
|  2 | Romatico  | Bad         |
|  3 | Pizza     | Great       |
|  4 | Metallica | Really cool |
|  5 | Lofi      | Really cool |
+----+-----------+-------------+

但最初使用如下index.js配置时,无法连接到该数据库:

const express = require('express');
const app = express();
const mysql = require('mysql');


const db = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "band_reviews",
});

db.connect((err) => {
    if(err){
        console.log('Error connecting to Db');
    } else { 
        console.log('Connection Established');
    }   
});

app.get("/", (req,res) => {
    const sql = "INSERT INTO band_reviews (bandName, bandReview) VALUES ('Owane','The Best');";
    db.query(sql, (err, result) => {
        if (!err) {
            console.log('Successfully added information.');
            } else {
            console.log('Was not able to add information to database.');
        }
        res.send("Testing DB Connection");
    });
});

db.end(function (err){
    //
});

app.listen(3001, () => {
        console.log('running on port 3001');
    });

package.json配置如下:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "devStart": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mysql": "^2.18.1",
    "nodemon": "^2.0.15"
  }
}

更新:已经解决了数据库连接问题,但仍然无法将记录成功插入到目标表中。


解决方案

你的代码存在核心逻辑错误:数据库连接在服务启动前就被主动关闭了。
你在定义接口逻辑之后、监听端口之前,直接调用了db.end()方法,这个方法会立即终止当前的数据库连接,等后续请求进来调用db.query时,已经没有可用的数据库连接,自然无法插入数据。

修复步骤

  1. 删掉代码中的db.end()相关代码,数据库长连接会在服务运行期间一直保持,不需要手动提前关闭。如果有特殊场景需要关闭连接,也应该放在查询的回调逻辑中执行,而不是全局初始化阶段就调用。
  2. 建议在查询报错的回调中打印具体的错误信息,方便后续排查问题,修改后的接口逻辑参考:
app.get("/", (req,res) => {
    const sql = "INSERT INTO band_reviews (bandName, bandReview) VALUES ('Owane','The Best');";
    db.query(sql, (err, result) => {
        if (!err) {
            console.log('Successfully added information.');
            res.send("插入成功");
        } else {
            console.log('插入失败,错误信息:', err);
            res.status(500).send("插入失败:" + err.message);
        }
    });
});
  1. 可选优化:目前使用的mysql包已经停止维护,建议替换为官方维护的mysql2包,兼容性更好,对MySQL 8.0+的特性支持更完善。替换方法:
    • 执行npm uninstall mysql && npm install mysql2
    • 将引入代码修改为const mysql = require('mysql2');,其余API和现有代码完全兼容,不需要额外修改。

修改完成后重启服务,访问http://localhost:3001即可正常插入数据。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:06:10