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

Node.js Express POST插入MySQL时id字段类型错误问题求助

问题解决:MySQL插入数据时id字段类型不匹配错误

错误原因

你的users表中id字段是整数类型(大概率是自增主键),但代码里手动给id赋值了空字符串'',MySQL无法将空字符串转换为合法整数,因此触发ER_TRUNCATED_WRONG_VALUE_FOR_FIELD错误。

解决方案

根据id字段的实际用途,选择以下处理方式:

1. 如果id是自增主键(最常见场景)

直接从postValue对象中移除id属性,让MySQL自动生成自增ID:

const insertData = (req,res)=>{
    console.log(req.body);
    var postValue ={
        username:req.body.username,
        usersalary:req.body.usersalary
    }

    db.query(`insert into users SET ? `, postValue ,function(err,results){
        if(err) throw err;
        res.send({msg:results});
    });
}

2. 如果id需要手动传入整数

确保前端传递合法的整数值,或者在代码中将空值转换为合法整数(比如设置默认值):

const insertData = (req,res)=>{
    console.log(req.body);
    var postValue ={
        username:req.body.username,
        // 将空值转为整数,或根据业务逻辑设置默认值
        id: req.body.id ? parseInt(req.body.id, 10) : 0,
        usersalary:req.body.usersalary
    }

    db.query(`insert into users SET ? `, postValue ,function(err,results){
        if(err) throw err;
        res.send({msg:results});
    });
}

3. 如果id允许为NULL

将id的值设为null而非空字符串:

const insertData = (req,res)=>{
    console.log(req.body);
    var postValue ={
        username:req.body.username,
        id: null,
        usersalary:req.body.usersalary
    }

    db.query(`insert into users SET ? `, postValue ,function(err,results){
        if(err) throw err;
        res.send({msg:results});
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 02:24:11