【问题标题】:Node js - Mysql query is not executed as codedNode js - Mysql 查询未按编码执行
【发布时间】:2022-01-08 23:05:02
【问题描述】:

我在 node.js 中创建了几个 sql 语句,现在我想在我的数据库上执行它们。但是,查询字符串不会按编码执行。

这是我生成查询字符串的函数。

function insertProducts(products) {
    if (!connection) {
        // Create MYSQL-Connection
        console.log('BUILDING connection to DB');
        connection = getConnection();
        connection.connect();
    }

    let query = "";
    for (let i = 0; i < products.length; i++) {
// Iterate trough the products array and create a sql query
        query += "INSERT INTO `tShortDescription`(`ShortDescription`, `Language`) VALUES ('" + products[i].short_description + "', 'DE'); " +
            "INSERT INTO `tDescription`(`Description`, `Language`) VALUES ('" + products[i].description + "', 'DE'); " +
            "INSERT INTO `tManufacturer`(`Name`) VALUES ('" + products[i].manufactur + "'); " +
            "INSERT INTO `tSupplier`(`Name`) VALUES ('" + products[i].supplier + "'); " +

            "INSERT INTO `tProduct`(`Sku`, `Title`, `ShortDescriptionId`, `DescriptionId`, `WohlesalePrice`, `SellingPrice`, `Quantity`, " +
            "`ManufacturerId`, `SupplierId`, `Ean`) VALUES ('" + products[i].sku + "', '" + products[i].name + "', " +
            "(SELECT id FROM tShortDescription WHERE ShortDescription = '" + products[i].short_description + "' LIMIT 1), " +
            "(SELECT id FROM tDescription WHERE Description LIKE '" + products[i].description + "' LIMIT 1), " +
            products[i].wholesale_price + ", " + products[i].selling_price + ", " + products[i].quantity + ", " +
            "(SELECT id FROM tManufacturer WHERE Name = '" + products[i].manufactur + "' LIMIT 1), " +
            "(SELECT id FROM tSupplier WHERE Name = '" + products[i].supplier + "' LIMIT 1), " + products[i].ean + "); ";

        for (let j = 0; j < products[i].categories.length; j++) {
            // Ad all categories to query
            query += "INSERT INTO `rtCategory`(`ProductId`, `CategoryId`) " +
                "VALUES ((SELECT `Id` FROM `tProduct` WHERE sku = '" + products[i].sku + "' LIMIT 1), " +
                "(SELECT `Id` FROM `tCategory` WHERE Id = " + products[i].categories[j].src + " LIMIT 1)); "

            for (let c = 0; c < products[i].images.length; c++) {
                // Ad all images to query
                query += "INSERT INTO `tImage`(`Url`) VALUES ('" + products[i].images[c].src + "'); " +
                    "INSERT INTO `rtImage`(`ProductId`, `ImageId`) " +
                    "VALUES ((SELECT `Id` FROM `tProduct` WHERE sku = '" + products[i].sku + "' LIMIT 1), " +
                    "(SELECT `Id` FROM `tImage` WHERE url = '" + products[i].images[c].src + "' LIMIT 1)); "
            }
        }
    }

    query = query.replace(/[\n\r\t]/g,);

    if (query != "") {
        // Create new Product in DB 
        return new Promise((resolve, reject) => {
            connection.query(query, function (error, results, fields) {
                if (error) { console.log(error) };
                console.log('INSERTING successful');
                resolve(results);
            });
        });
    } else {
        console.log('There are no new products to insert in db');
    }
}

如果我 console.log(query)(在我的数据库上执行查询之前)并直接在 php myadmin 中执行字符串,一切正常,但如果我在 connection.query(query, function (error, results, fields)..... 之类的代码中执行查询,我会遇到几个错误。

终端中的错误消息:

code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "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 'INSERT INTO `tDescription`(`Description`, `Language`) VALUES ('<p><strong>Tantra' at line 1",
  sqlState: '42000',
  index: 0,

由于错误,我还在终端中返回了 sql 查询,如果我直接在 php myadmin 中执行此查询,我也会收到错误 ->

SQL query: Documentation


INSERT INTO `rtImage`(`ProductId`, `ImageId`) VALUES ((SELECT `Id` FROM `tProduct` WHERE sku = 'H1500148' LM 
IT 1), (SELECT `Id` FROM `tImage` WHERE url = 'https://cdnbigbuy.com/images/H1500148_409897.jpg' LIMIT 1))
MySQL said: Documentation

#1064 - 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 'LM
IT 1), (SELECT `Id` FROM `tImage` WHERE url = 'https://cdnbigbuy.com/images' at line 1

看起来 LIMIT 以某种方式被分割了...use near 'LM IT 1)....

我希望您了解问题出在哪里,并且有人可能会提供提示。

【问题讨论】:

  • 你写的是LM IT而不是LIMIT。我强烈建议使用模板文字而不是 '+'
  • LM IT 是从 sql 生成的。在我的 node.js 代码中,我写了LIMIT。这真是令人困惑。感谢您提供有关模板文字的提示,我会尝试但我认为这不能解决我的问题

标签: mysql node.js


【解决方案1】:

您的查询被处理为“限制”,它只是控制台中出现错误的新行。

在任何情况下,您都不应该对 SQL 查询使用字符串连接(甚至模板文字),因为 1. 这很可能是您的问题的根源。 2. 允许SQL注入攻击,非常危险。

改用参数。这是一个例子:

connection.query("SELECT * FROM bank_accounts WHERE dob = ? AND bank_account = ?",[
     req.body.dob,
     req.body.account_number
    ],function(error, results){});

阅读更多关于 SQL 注入和占位符的信息read this article.

【讨论】:

    【解决方案2】:

    感谢您提供有用的提示。

    问题是我没有在我的代码中设置multiple statements: true。这个var默认为false,应该为true,否则一次请求一次执行多个查询是不可能的!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 2012-12-24
      相关资源
      最近更新 更多