在jdbc中,preparedStatement是如何防止SQL注入的

来源:互联网 发布:淘宝天下小二 编辑:程序博客网 时间:2024/06/04 18:25

对于JDBC而言,SQL注入攻击只对Statement有效,对PreparedStatement是无效的,这是因为PreparedStatement不允许在插入时改变查询的逻辑结构.


如果有一条SQL语句: "select * from 表 where 用户名 = '用户名'"

Statement的SQL语句是这样写的: "select * from 表 where 用户名 = '"+ 变量值 +"'"
PreparedStatement的SQL语句是这样写的: "select * from 表 where 用户名 = ?" 然后对应?赋值
这样我们就发现输入 "aa' or '1' = '1"
Statement是将这个和SQL语句做字符串连接到一起执行
PreparedStatement是将 "aa' or '1' = '1" 作为一个字符串赋值给?,做为"用户名"字段的对应值,显然这样SQL注入无从谈起了.