How to use parameters in SQL statement table names in MyBatis
INSERT INTO Prefix_${table_name} (a, B, c) VALUES (#{a}, #{b}, #{c})
${} indicates direct use literal (literal value)
#{} indicates that this is a parameter
If table_name is "ABC"
Then ${table_name} is ABC
#{table_name} is "ABC"
Java code
- 1. #可以进行预编译, type match, #变量名 # will be converted to the type of JDBC
- $ does not perform data type matching, $ variable name $ directly replaces $name $ with the contents of name
- For example:
- SELECT * FROM tablename where id = #id #, assuming the value of ID is 12, where if the database field ID is a character type, then #id# represents ' 12 ', if the ID is integer, then #id# is
- SELECT * FROM TableName where id= will be converted to JDBC? Put parameter is set to the value of ID
- SELECT * FROM tablename WHERE id = $id $, if the field ID is integer, the SQL statement does not go wrong, but if the field ID is a character type,
- Then the SQL statement should be written as a select * from table where id = ' $id $ '
- 3. #方式能够很大程度防止sql注入.
- The 4.$ method does not prevent SQL injection.
- The 5.$ method is typically used to pass in database objects. For example, incoming table names.
- 6. So ibatis use # better than $, generally can use the # do not use $.
- In addition, use # #可以指定参数对应数据库的类型
- Such as:
- SELECT * FROM tablename WHERE id = #id: number#
- Pay special attention when doing in,like operation
- Summarize the following:
- The $ number used in the specific Pojo class is also the non-basic type of the value, while the # number is used in the specific base type of the value
- <sql id="Update_by_example_where_clause" >
- <where>
- <foreach collection="Example.oredcriteria" item="Criteria" separator="or" >
- <if test="Criteria.valid" >
- <trim prefix="(" Prefixoverrides="and" suffix=")" >
- <foreach collection="Criteria.criteria" item="criterion" >
- <choose>
- <when test="Criterion.novalue" >
- and ${criterion.condition}
- </when>
- <when test="Criterion.singlevalue" >
- and ${criterion.condition} #{criterion.value}
- </when>
- <when test="Criterion.betweenvalue" >
- and ${criterion.condition} #{criterion.value} and #{criterion.secondvalue}
- </when>
- <when test="Criterion.listvalue" >
- and ${criterion.condition}
- <foreach close=")" collection="Criterion.value" item="ListItem" open= "(" separator="," >
- #{listitem}
- </foreach>
- </when>
- </choose>
- </foreach>
- </trim>
- </if>
- </foreach>
- </where>
- </sql>
[]ibatis symbol differs from dollar sign (#, $)