Home > php教程 > PHP开发 > body text

A brief discussion on the difference between # and $ in mybatis and how to prevent SQL injection

高洛峰
Release: 2017-01-05 17:21:49
Original
1879 people have browsed it

The difference between # and $ in mybatis

1. #Treat the incoming data as a string, and add a double quotation mark to the automatically incoming data. For example: order by #user_id#, if the value passed in is 111, then the value when parsed into sql is order by "111". If the value passed in is id, the parsed sql is order by "id".
 
2. $ Display the incoming data directly and generate it in sql. For example: order by $user_id$, if the value passed in is 111, then the value when parsed into sql is order by user_id. If the value passed in is id, the parsed sql is order by id.
 
3. #Method can prevent sql injection to a great extent.
 
4.$ method cannot prevent Sql injection.


5. The $ method is generally used to pass in database objects, such as table names.
 
6. If you can generally use #, don’t use $.

Prevent Sql injection

Note: Do not write the SQL statement as select * from t_stu where s_name like '%$name$%', which is extremely vulnerable to injection attacks.

Parameters in the format of "${xxx}" will directly participate in sql compilation, so injection attacks cannot be avoided. But when it comes to dynamic table names and column names, only parameter formats such as "${xxx}" can be used.

When writing the mapping statement of mybatis, try to use the format of "#{xxx}". If you have to use parameters such as "${xxx}", you must manually filter them to prevent SQL injection attacks.

Example

<sql id="condition_where"> 
  <isNotEmpty property="companyName" prepend=" and "> 
    t1.company_name like #companyName# 
  </isNotEmpty> 
</sql>
Copy after login


The java code is similar to your original one, and there is nothing wrong with it. If you find it troublesome, set the judgment to null and '%' can be encapsulated into a method

if (!StringUtil.isEmpty(this.companyName)) { 
  table.setCompanyName("%" + this.companyName + "%"); 
}
Copy after login


The above is a brief discussion of # and in mybatis brought to you by the editor The difference between $ and the method to prevent sql injection is all covered. I hope everyone will support the PHP Chinese website~

For more about the difference between # and $ in mybatis and the method to prevent sql injection, please pay attention to PHP for related articles Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template