简体   繁体   English

为什么我的SQL代码出现语法错误?

[英]How come I'm getting a syntax error in my SQL code?

I'm getting an error on the line that says 我在一行上看到一个错误

const INSERT_PRODUCTS_QUERY = 'INSERT INTO products(name, price) VALUES('${name}',${price})';

I know the error emanates from the single quotes in '${name}' but I also tried removing the single quotes in an attempt to get rid of this error and still get an error that says: 我知道错误是由'${name}'的单引号引起的,但我也尝试删除单引号,以消除该错误并仍然显示以下错误:

{
"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 '{name}, ${price})' at line 1",
"sqlState": "42000",
"index": 0,
"sql": "INSERT INTO products(name, price) VALUES(${name}, ${price})"
}

Here's my code: 这是我的代码:

const express = require('express');
const cors = require('cors');
const mysql = require('mysql');

const app = express();

const SELECT_ALL_PRODUCTS_QUERY = 'SELECT * FROM products';

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'react_sql'
});

connection.connect(err => {
    if(err) {
        return err;
    }
});

app.use(cors());

app.get('/', (req, res) => {
    res.send('go to /products to see products')
});

app.get('/products/add', (req, res) => {
    const { name, price } = req.query;
    const INSERT_PRODUCTS_QUERY = 'INSERT INTO products(name, price) VALUES('${name}',${price})';

    connection.query(INSERT_PRODUCTS_QUERY, (err, results) => {
       if(err) {
           return res.send(err);
       } else {
           return res.send('successfully added products');
       }
    });

})

app.get('/products', (req, res) => {
    connection.query(SELECT_ALL_PRODUCTS_QUERY, (err, results) => {
        if(err) {
            return res.send(err)
        } else {
            return res.json({
                data: results
            })
        }
    });
});

app.listen(4000, () => {
    console.log("listening port 4000");
});

I don't know so much about SQL and its queries, so for this subject (strings, security, etc) listen to other people. 我对SQL及其查询的了解不多,因此对于这个主题(字符串,安全性等),请听别人讲。

As you can see in the comments this opens the code to SQL Injections, better avoid to using it. 正如您在注释中看到的那样,这会将代码打开到SQL Injections,最好避免使用它。

Thanks, @Keith. 谢谢,@基思。


But if you want to use variables in your strings either you need to combine different string pieces or you should use template literals . 但是,如果要在字符串中使用变量,则需要组合不同的字符串或使用模板文字

PS: If you still really, really want to use template literals, you can check this node package which is sql-template-strings for NodeJS. PS:如果您仍然非常想使用模板文字,则可以检查此节点包 ,它是sql-template-strings

Notice the backticks: `` 注意反引号:

 const name = "foo"; const price = 100; const INSERT_PRODUCTS_QUERY = `INSERT INTO products(name, price) VALUES('${name}',${price})`; console.log( INSERT_PRODUCTS_QUERY ); 

SQL parameters in MySQL are not only a convenient way of passing parameters to query's, there also a must if you don't want to open your site to SQL Injection problems. MySQL中的SQL参数不仅是将参数传递给查询的一种便捷方法,而且如果您不想因SQL注入问题而打开自己的站点,这也是必须的。

The changes you need to make are very minimal.. 您需要进行的更改非常少。

First change your query to -> 首先将查询更改为->

const INSERT_PRODUCTS_QUERY = 
   'INSERT INTO products(name, price) VALUES(?, ?)'

And when you use this query pass the parameters as the second parameter. 当您使用此查询时,将参数作为第二个参数传递。

connection.query(SELECT_ALL_PRODUCTS_QUERY, 
  [name, price],
  (err, results) => {

Template literals are not surrounded by simple quotes but by back-ticks "`" 模板文字不是用简单的引号引起来,而是用反引号“`”引起来

It should become : 它应该变成:

const INSERT_PRODUCTS_QUERY =  `INSERT INTO products(name, price) VALUES('${name}',${price})`

You are not providing literals correctly, modify your query as following, this is PHP representation you can change accordingly. 您没有正确提供文字,请按以下方式修改查询,这是可以相应更改的PHP表示形式。

INSERT INTO products(name, price) VALUES('".${name}."','".${price}."');

Single quote for literal value is ambiguous with language single quote, which breaks query syntax. 文字值的单引号与语言单引号是不明确的,这破坏了查询语法。

This is not best way to achieve this, as it opens your query to SQL Injection. 这不是实现此目的的最佳方法,因为它打开了对SQL Injection的查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的 javascript 代码中是否有任何错误? 答案应该是百分比,但我得到了不同的 output - Is there any error in my javascript code? The answer is supposed to come in percentage but I'm getting a different output 我的代码在使用箭头功能和使用{}的情况下运行良好,但是在删除{}时出现语法错误 - My code runs well with arrow function and using { }, but when { } are removed i'm getting syntax error 获取语​​法错误我的代码 - Getting syntax error my code 我收到 Postgresql 的 created_on 日期的语法错误 - I'm getting a syntax error for the date created_on for Postgresql 我在这些行中遇到了一些语法错误 - I'm getting a syntax error involving something in these lines 我想获取我的 Graph API 令牌,但出现错误,我正在使用 HttpServices 发出 POST 请求。 我收到 400 状态码。 我正在使用 NestJS - I want to get my Graph API token but I got an error, I'm making a POST request with HttpServices. I'm getting a 400 status code. I'm using NestJS 使用javascript / jquery在子字符串中查找关键字-我的代码中出现类型错误 - Find keywords in a substring using javascript/jquery - I'm getting a type error in my code 在我的 javascript 代码中使用 spawn 运行 python 时出现错误 - I'm getting an error when using spawn to run python in my javascript code 我的代码是对的,但是eslint报错,怎么回事? - My code is right,but eslint give me a error, how does it come? 为什么我在 node.js 代码中使用 sql 时出现语法错误 - why i have syntax error when i use sql in my node.js code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM