NodeJS使用tedious连接SQL Server插入数据报错如何解决?
问题排查与解决方案
错误1:ReferenceError: fetch is not defined
原因
Node.js v18以下版本没有内置浏览器端的fetch API,直接调用会报未定义错误。同时你代码中使用的lstUnValid数组未提前声明,运行时也会触发未定义报错。
解决步骤
- 安装兼容CommonJS规范的
node-fetch包,执行命令:
npm install node-fetch@2
- 在代码顶部引入依赖并声明缺失的数组:
var fetch = require('node-fetch'); var lstUnValid = [];
错误2:Requests can only be made in the LoggedIn state, not the Connecting state + 插入时lstValid[1]为空问题
原因
- 数据库连接回调没有判断错误,若连接失败仍会执行插入请求,此时连接处于
Connecting状态就会触发该报错。 calcWeather是异步函数,你调用时没有加await等待执行完成,且函数内部的天气接口请求也没有等待全部返回,执行插入逻辑时lstValid数组还没有被赋值,甚至数据库连接还未完全就绪。- 插入参数赋值错误,你直接把整个对象
lstValid[1]传给IdOficina字段,类型不匹配也会触发插入失败。
解决步骤
- 优化数据库连接回调,先判断连接错误:
connection.on("connect", function (err) { if (err) { console.error("数据库连接失败:", err); return; } console.log("连接成功"); executeStatement1(); });
- 修改
calcWeather函数,等待所有天气接口请求完成再返回:
async function calcWeather() { const info = await fetch("../json/data.json") .then(function (response) { return response.json(); }); const fetchPromises = []; for (var i in info) { const _idOficina = info[i][0].IdOficina; const lat = info[i][0].latjson; const long = info[i][0].lonjson; const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`; fetchPromises.push( fetch(base) .then((responses) => responses.json()) .then((data) => { var myObject = { Id_Oficina: _idOficina, Temperatura: data.main.temp, Humedad: data.main.humidity, Nubes: data.clouds.all, Sensacion: data.main.feels_like, Descripcion: data.weather[0].description // 其余属性按需求补全 }; if (myObject.Temperatura < 99) { lstValid.push(myObject); } else { lstUnValid.push(myObject); } }) ); } await Promise.all(fetchPromises); }
- 修改
executeStatement1为异步函数,等待数据处理完成后再执行插入,同时修正参数赋值逻辑:
async function executeStatement1() { await calcWeather(); // 提前判断有效数据长度,避免下标越界 if (lstValid.length < 2) { console.error("有效数据不足,当前长度:", lstValid.length); connection.close(); return; } const targetItem = lstValid[1]; const request = new Request( "INSERT INTO TB_BI_CSL_RegistroTemperaturaXidOdicina (IdOficina, Humedad, Nubes, Sensacion, Temperatura, Descripcion) VALUES (@IdOficina, @Humedad, @Nubes, @Sensacion, @Temperatura, @Descripcion)", function (err) { if (err) { console.log("插入失败:", err); connection.close(); } } ); request.addParameter("IdOficina", TYPES.SmallInt, targetItem.Id_Oficina); request.addParameter("Humedad", TYPES.Float, targetItem.Humedad); request.addParameter("Nubes", TYPES.Int, targetItem.Nubes); request.addParameter("Sensacion", TYPES.Float, targetItem.Sensacion); request.addParameter("Temperatura", TYPES.Float, targetItem.Temperatura); request.addParameter("Descripcion", TYPES.NVarChar, targetItem.Descripcion); request.on("row", function (columns) { columns.forEach(function (column) { if (column.value === null) { console.log("NULL"); } else { console.log("值插入成功"); } }); }); request.on("requestCompleted", function (rowCount, more) { console.log("请求完成,影响行数:", rowCount); connection.close(); }); connection.execSql(request); }
内容的提问来源于stack exchange,提问作者Martín JF
相关产品推荐
相关产品推荐

