NodeJS:无法将数据保存到 MySQL

Posted

技术标签:

【中文标题】NodeJS:无法将数据保存到 MySQL【英文标题】:NodeJS: Unable to save data to MySQL 【发布时间】:2021-10-26 05:51:27 【问题描述】:

我将以下 JSON 数组发送到代码

[
    
        "idseller_portfolio_item": 1,
        "image_url": "https:://something.com/image3.png"
    ,
    
        "idseller_portfolio_item": 1,
        "image_url": "https:://something.com/image4.png"
    
]

我需要读取 JSON 数组并将数据插入数据库。下面是我的代码,我正在尝试批量插入。

const mysql = require('mysql2');
const errorCodes = require('source/error-codes');
const PropertiesReader = require('properties-reader');

const prop = PropertiesReader('properties.properties');

const con = mysql.createConnection(
    host: prop.get('server.host'),
    user: prop.get("server.username"),
    password: prop.get("server.password"),
    port: prop.get("server.port"),
    database: prop.get("server.dbname")
);


exports.saveSellerPortfolioItemImages = (event, context, callback) => 

    context.callbackWaitsForEmptyEventLoop = false;

    if (event.body == null && event.body == undefined) 
        var response = errorCodes.missing_parameters;
        callback(null, response)
    
    else 
        let body = JSON.parse(event.body)
        console.log("body", body);
        

            let result = [];

            for(let i in body)
                result.push([i, body [i]]);

            console.log("MyResult: "+ result);

            //allows for using callbacks as finish/error-handlers
            const sql = "INSERT INTO seller_portfolio_item_images (idseller_portfolio_item, image_url) VALUES ?";
            con.execute(sql, [result], function (err, result) 
                if (err) 
                    console.log(err.toString());

                    if (err.toString().indexOf('cannot be null') >= 0) 
                        var response = errorCodes.not_null_parameters;
                        callback(null, response);
                    
                    var response = errorCodes.internal_server_error;
                    callback(null, response);

                
                else 
                    var response = 
                        "statusCode": 200,
                        "headers": 
                            "Content-Type": "application/json"
                        ,
                        "body": JSON.stringify( insertId: result.insertId ),
                        "isBase64Encoded": false
                    ;
                    callback(null, response)
                
            );
        


    
;

这是我的桌子

但是,这给了我以下错误。 primary key 是自动生成的,所以我不必从我的代码中插入它。

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1

这里有什么问题?

【问题讨论】:

let body = JSON.parse(event.body), 身体是什么?你能告诉我们console.debug(body)吗? 尝试将VALUES ?更改为VALUES (?) (idseller_portfolio_item, image_url) VALUES ? 有两列但只有一个值。这应该是(idseller_portfolio_item, image_url) VALUES (?, ?) 【参考方案1】:

“?”在查询中告诉一个参数将来自一个数组 所以如果你想添加两个参数,你会使用 (?,?) 等等

            //allows for using callbacks as finish/error-handlers
            const sql = "INSERT INTO seller_portfolio_item_images (idseller_portfolio_item, image_url) VALUES ?";
            con.execute(sql, [result], function (err, result) 

所以,在您的情况下,您需要按如下方式进行更改-

const mysql = require('mysql2');
const errorCodes = require('source/error-codes');
const PropertiesReader = require('properties-reader');

const prop = PropertiesReader('properties.properties');

const con = mysql.createConnection(
    host: prop.get('server.host'),
    user: prop.get("server.username"),
    password: prop.get("server.password"),
    port: prop.get("server.port"),
    database: prop.get("server.dbname")
);


exports.saveSellerPortfolioItemImages = (event, context, callback) => 

    context.callbackWaitsForEmptyEventLoop = false;

    if (event.body == null && event.body == undefined) 
        var response = errorCodes.missing_parameters;
        callback(null, response)
    
    else 
        let body = JSON.parse(event.body)
        console.log("body", body);
        
//-------------------updated-------------------------------
         //   let result = [];

            for(let i in body)
               // result.push([i, body [i]]);

            console.log("MyResult: "+ result);

            //allows for using callbacks as finish/error-handlers
            const sql = "INSERT INTO seller_portfolio_item_images (idseller_portfolio_item, image_url) VALUES (?,?)";
            con.execute(sql, [body[i].idseller_portfolio_item,body[i].image_url], function (err, result) 
                if (err) 
                    console.log(err.toString());

                    if (err.toString().indexOf('cannot be null') >= 0) 
                        var response = errorCodes.not_null_parameters;
                        callback(null, response);
                    
                    var response = errorCodes.internal_server_error;
                    callback(null, response);

                
                else 
                    var response = 
                        "statusCode": 200,
                        "headers": 
                            "Content-Type": "application/json"
                        ,
                        "body": JSON.stringify( insertId: result.insertId ),
                        "isBase64Encoded": false
                    ;
                    callback(null, response)
                
            );
        

//-------------------end-------------------------------

    
;

【讨论】:

谢谢。您的代码有效。但我注意到它仅在数组中只有 2 个元素时才有效。如果超过 2 个,则不会插入其余元素。这是为什么?

以上是关于NodeJS:无法将数据保存到 MySQL的主要内容,如果未能解决你的问题,请参考以下文章

NodeJS:将 JSON 保存到 MongoDB

无法将插入的值保存到 tableview 和 mySQL - PHP

表单不会将数据保存到 mySQL 表中

AngularJS、NodeJS:将数据保存到 Json 文件或数据库

使用Azure Functions中的NodeJS将文件保存到Azure Data Lake Storage的任何示例?

将十六进制数据保存到 NodeJS 中的文件