MyBatis SQL 注入案例

安全的用法

<select id="getPerson" parameterType="int" resultType="org.application.vo.Person">
SELECT * FROM PERSON WHERE ID = #{id}
</select>

使用 #{} 传参数 会使用PreparedStatement 执行sql 例如:

/* Comparable JDBC code */
String selectPerson = "SELECT * FROM PERSON WHERE ID = ?"; 
PreparedStatement ps = conn.prepareStatement(selectPerson); 
ps.setInt(1, id);

其他一些正确案例

<insert id="insertPerson" parameterType="org.application.vo.Person">
insert into Person (id, name, email, phone)
values (#{id}, #{name}, #{email}, #{phone})
</insert>
 
<update id="updatePerson" parameterType="org.application.vo.Person">
update Person set name = #{name}, email = #{email}, phone = #{phone}
where id = #{id}
</update>
 
<delete id="deletePerson" parameterType="int">
delete from Person where id = #{id}
</delete>

易受攻击的用法

<select id="getPerson" parameterType="string" resultType="org.application.vo.Person">
SELECT * FROM PERSON WHERE NAME = #{name} AND PHONE LIKE '${phone}'; 
</select>
如果入参是: "1%' OR '1'='1"
SELECT * FROM PERSON WHERE NAME = ? and PHONE LIKE '1%' OR '1' = '1'
如果入参是:"A%'; DELETE FROM PERSON; --"
SELECT * FROM PERSON WHERE NAME = ? and PHONE LIKE 'A%'; DELETE FROM PERSON; --'

其他一些错误案例

<insert id="insertPerson" parameterType="org.application.vo.Person">
insert into Person (id, name, email, phone)
values (#{id}, #{name}, #{email}, ${phone})
</insert>
 
<update id="updatePerson" parameterType="org.application.vo.Person">
update Person set phone = ${phone}
where id = #{id}
</update>
  
<delete id="deletePerson" parameterType="int">
delete from Person where id = ${id}
</delete>