Node.js使用mssql向SQL Server插入JSON对象及空值处理问题
mssql插入JSON对象两个问题的解决方案
错误1:Incorrect syntax near the keyword 'SET'
该报错有两个原因:
INSERT INTO <表名> SET <字段=值>是MySQL的专属语法,SQL Server不支持该语法格式- 官方
mssql驱动不支持直接传入JSON对象替换单个?占位符的简化写法
错误2:varchar值'null'转INT类型失败
手动拼接SQL字符串时,JS的null值会被转为'null'字符串,你又给所有值统一加了单引号,导致插入INT字段时触发类型转换报错。同时手动拼接SQL存在SQL注入风险,禁止在生产环境使用。
正确实现代码
无需手动编写逐个参数,可通过遍历JSON对象自动生成插入语句与绑定参数,驱动会自动处理NULL值的类型转换:
// 把原来错误的插入代码段替换为以下逻辑 if(buildingValidationResult.valid){ const request = pool.request() const columns = [] const paramPlaceholders = [] // 遍历你组装好的buildingData对象,自动绑定参数 Object.entries(buildingData).forEach(([key, value], index) => { columns.push(key) const paramName = `param${index}` paramPlaceholders.push(`@${paramName}`) // 自动绑定参数,驱动会识别JS null转为SQL的NULL request.input(paramName, value) }) // 自动生成合法的SQL Server插入语句 const insertSql = `INSERT INTO building (${columns.join(',')}) VALUES (${paramPlaceholders.join(',')})` const insertResult = await request.query(insertSql) if(insertResult.rowsAffected[0] === 1){ console.log("Building inserted: " + JSON.stringify(insertResult)); res.status(201).send("Building data inserted Successfully!").end(); } }
补充说明
如果需要严格指定字段类型,可以在request.input的第二个参数传入mssql模块暴露的类型常量,比如INT字段可写为request.input(paramName, mssql.Int, value),绝大多数场景下驱动可以自动识别字段类型,无需额外指定。
内容的提问来源于stack exchange,提问作者Lakshesh Girdhar
相关产品推荐
相关产品推荐

