你需要在 Mysql 参数周围加括号来防止 sql 注入吗? [英] Do you need brackets around Mysql parameters to prevent sql injection?

查看:31
本文介绍了你需要在 Mysql 参数周围加括号来防止 sql 注入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 nodejs 和 mysql npm 包,我正在尝试从 other_text =

I am using nodejs and the mysql npm package and I'm trying to select from a table where other_text =

这是它的样子:

var query = connection.query(`SELECT id FROM ${tableName} WHERE other_text = ?`,
    attributeName.other_text, function (err, rows) {
    ...

我已经阅读了使用 ?将自动转义用户输入的字符串.在我看到的大多数执行此操作的示例中,它们在查询函数中的第二个参数周围都有括号,如下所示:

I have read that using ? will automatically escape the user entered string. In most of the examples that I see that do this, they have brackets around the 2nd parameter in the query function, like below:

var query = connection.query(`SELECT id FROM ${tableName} WHERE other_text = ?`,
    [attributeName.other_text], function (err, rows) {
    ...

为了转义传入的字符串是否需要括号?当我尝试它时它可以工作,但我什至不知道如何测试 SQL 注入,所以我真的不知道括号是否必要甚至正确.

Are the brackets necessary in order to escape the string that's passed in? It works when I try it, but I don't even know how to test a SQL injection so I don't really know if the brackets are necessary or even correct.

谢谢.

推荐答案

括号代表一个数组.如果您有更多要用于查询的值,您可以使用数组.

The brackets represent an array. You can use an array in case you have more values you want to use with your query.

例如,假设您想从表中选择多个列,并且您想将它们传递给语句,您可以使用如下代码:

For example, let's say that you want to select multiple columns from the table, and you want to pass them to the statement, you would use something like this:

connection.query(`SELECT ?? FROM ${tableName}`,
[col1, col2, col3], function (err, rows) {

它还可以与字符串、数字甚至对象结合使用.假设您要更新用户表中 id 为 1 的用户.你会做这样的事情:

It also does work in combination with strings, numbers or even objects. Let's say that you want to update the user with id 1 from Users table table. You would do something like this:

const tableName = 'users';
const whereCondition = {id: 1};
const whaToUpdate = {name: 'newName'}
const mysql = require('mysql');
const statement = mysql.format('update ?? set ? where ?', [tableName, whaToUpdate , whereCondition]);

我还建议使用 .format 来更好地阅读代码.最后你会得到这样的东西:

I also recommend using .format for better code reading. Finally you would have something like this:

connection.query(statement, (error, result, fields) => { });

这篇关于你需要在 Mysql 参数周围加括号来防止 sql 注入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆