The difference between # and $ in MyBatis and the prevention of SQL injection

Source: Internet
Author: User
Tags sql injection

Disclaimer: This is reproduced.

The difference between # and $ in MyBatis
1. #将传入的数据都当成一个字符串, a double quotation mark is added to the automatically passed data. For example: ORDER by #user_id #, if the value passed in is 111, then the value parsed into SQL is Order by "111", and if the value passed in is an ID, then the parsed SQL is the ORDER by "id".
  
2. $ direct display of incoming data is generated in SQL. For example: ORDER by $user _id$, if the value passed in is 111, then the value to parse to SQL is Order by user_id, and if the value passed in is ID, the parsed SQL is the order by ID.
  
3. #方式能够很大程度防止sql注入.
  
The 4.$ method does not prevent SQL injection.


The 5.$ method is typically used to pass in database objects, such as incoming table names.
  
6. Do not use the $ in general.


Prevent SQL injection

NOTE: The SQL statement is not written as a select * from T_stu where s_name like '% $name $% ', which is extremely susceptible to injection attacks.

Parameters of the format "${xxx}" are directly involved in SQL compilation, thus preventing injection attacks. But when it comes to dynamic table names and column names, you can only use parameter formats such as "${xxx}".
When writing MyBatis mapping statements, use the format "#{xxx}" as much as possible. If you have to use parameters such as "${xxx}", do the filtering work manually to prevent SQL injection attacks.

<sql id= "Condition_where" >        <isnotempty property= "CompanyName" prepend= "and" >            t1.company_name Like #companyName #        </isNotEmpty>    </sql>   

 

Java code and your original similar, in fact, nothing bad, you have to feel trouble to judge null and '% ' package into a method can be

if (! Stringutil.isempty (this. CompanyName)) {        table.setcompanyname (this. CompanyName + "% ");    }  

The difference between # and $ in MyBatis and the prevention of SQL injection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.