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

为何NodeJS代码无法删除MySQL数据库记录?求排查

问题分析与解决方案

核心问题:未提交事务

你的代码启动了数据库事务,但执行完DELETE操作后没有提交事务,导致所有修改被自动回滚,数据库没有任何变化。

代码中调用了await connection.beginTransaction()开启事务,但整个try块内仅执行了删除语句,缺少关键的await connection.commit()步骤。当事务未手动提交时,连接释放后数据库会自动回滚该事务,删除操作根本不会生效。

修复方案

在DELETE执行完成后,添加事务提交操作:

try {
    await connection.beginTransaction();

    const currentDateTime = new Date();
    currentDateTime.setMonth(currentDateTime.getMonth() - 2);

    console.log(currentDateTime.toLocaleDateString());

    const deleteFcmSql = "DELETE FROM fcm WHERE date_created < :date ";
    const deleteFcmResult = await connection.query(deleteFcmSql, {date:currentDateTime});
    
    // 新增:提交事务,让删除操作生效
    await connection.commit();
    console.log(`成功删除 ${deleteFcmResult[0].affectedRows} 条记录`);

} catch (error) {
    console.log(error);
    await connection.rollback();
    return errorCodes.save_failed;
    
} finally{
    connection.release();
}

额外优化:避免时区问题

JavaScript的Date对象依赖本地时区,若数据库存储的是UTC时间,可能导致日期比较不符合预期。推荐直接在SQL中计算两个月前的时间,完全规避时区差异:

try {
    await connection.beginTransaction();

    // 用MySQL内置函数计算两个月前的时间,无需JS处理日期
    const deleteFcmSql = "DELETE FROM fcm WHERE date_created < DATE_SUB(NOW(), INTERVAL 2 MONTH)";
    const deleteFcmResult = await connection.query(deleteFcmSql);
    
    await connection.commit();
    console.log(`成功删除 ${deleteFcmResult[0].affectedRows} 条记录`);

} catch (error) {
    console.log(error);
    await connection.rollback();
    return errorCodes.save_failed;
    
} finally{
    connection.release();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:25:39