簡體   English   中英

Nodejs 和 SQL - 使用多個 select 語句將數據插入 SQL 時出現問題

[英]Nodejs and SQL - Issue with inserting data to SQL using multiple select statements

錯誤圖片
通過使用多個 select 語句在 SQL 數據庫表 user_recipe_consumption 中插入數據時,我遇到了錯誤,因為 - throw err; // 重新拋出非 MySQL 錯誤 ^ 錯誤:ER_PARSE_ERROR:您的 SQL 語法有錯誤; 檢查與您的 MySQL 服務器版本相對應的手冊,以獲得在“蘑菇意大利面”附近使用的正確語法);','(select vegEmission from RecipeEmissions where RecipeName' 在第 1 行

for (var dataVal = 0; dataVal < req.body.length; dataVal++) {
    var recipeInfo = req.body[dataVal].RecipeName;
    var deviceID = req.body[dataVal].deviceID;
    var totEmission = req.body[dataVal].totalEmission;
    var sql = "INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry) VALUES ('" + deviceID + "','" + totEmission + "', '( select RecipeID, from RecipeEmissions where RecipeName = ?);' , '( select vegEmission from RecipeEmissions where RecipeName = ? );' ,'" + now + "')";              
    con.query(sql, recipeInfo, function(err, result) {
            if (err) throw err;
            console.log("Number of records inserted: " + result.affectedRows);
        });
    }

而不是 SQL 與 var 連接(以及與數據類型和 SQL 注入相關的問題),您應該使用完全基於參數綁定的查詢(例如:命名參數)。 您還應該使用插入 select 語法,而不是同一個表中的幾個 select

"INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry) 
SELECT :deviceID, :totEmissino,  RecipeID, vegEmission, :date_of_entry 
FROM RecipeEmissions 
where RecipeName = :RecipeName;"

例如:

connection.execute(
    "INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry) 
    SELECT :deviceID, :totEmission ,  RecipeID, vegEmission, :date_of_entry 
    FROM RecipeEmissions 
    WHERE RecipeName = :RecipeName;",
    {deviceID: deviceID, totEmission: totEmission, date_of_entry:date_of_entry,RecipeName:RecipeName},
function(err, result)
.......

您的 SQL 語句中有太多分號。 您還在子查詢周圍加上單引號,這有效地將其轉換為字符串文字。 而且您使用NOW()不正確。 嘗試這個:

var sql = "INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry) VALUES ('" + deviceID + "','" + totEmission + "', ( select RecipeID, from RecipeEmissions where RecipeName = ?) , ( select vegEmission from RecipeEmissions where RecipeName = ? ) , NOW())";

如果您的意思是now成為一個 JS 變量,那么您可以將查詢的那部分恢復為您原來的內容,但不清楚now應該包含什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM