PreparedStatement的setObject作用

在了解setObject作用前讲解一下PreparedStatement这个接口,然后循序渐进从setXxx()方法讲解到setObject。

PreparedStatement

java.sql包中的PreparedStatement接口继承了Statement接口,PreparedStatement对象可以防止sql注入,而Statement不能防止sql注入,所以实际开发的时候千万不要使用Statement。

SQL注入:

比如我的SQL语句为:

select * from user where username =' zhangsan' username ' and password ='password ' ;

其中传入的参数为:username(用户名) 和 password(密码)。

恶意注入之前的含意是查询user表的所有字段,匹配条件是username和password跟数据表的某条数据完全匹配使得条件成立,换言之就是用户名和密码必须都为正确的才可以查询到数据。

恶意注入方式一:输入 username: 随意 password: ’ or ‘1’='1

select * from user where username ='xxxxx' and password ='xxx' or '1'='1'; 

and 优先级 执行 高于 or

恶意注入方式二、在SQL添加 – 是mysql的注释 用户名框:输入 zhangsan’ 空格–空格 password 随意输入即可

select * from user where username ='zhangsan' -- ' and password ='' ;

注意:以上的 zhangsan’ 空格–空格 中的zhangsan是数据库存在的

setObject

setObject就是给JDBC的SQL语句的占位符赋值的,即是下面的“?”

预编译的SQL:参数使用?作为占位符

注意:sql的参数使用?作为占位符。 如:

select * from user where username = ? and password = ?;

获取执行sql语句的对象 PreparedStatement Connection.prepareStatement(String sql)

给?赋值:(Xxx代表参数类型)

  • 方法: setXxx(参数1,参数2)
  • 参数1:?的位置编号 从1 开始
  • 参数2:?的值

例如:

setString(1,"one")就是定义参数类型为String类型,然后给第一个?位置上赋值为one。

select * from user where username = 'one' and password = ?;

setInt(2,2)就是定义参数类型为Int类型,然后给第二个?的位置上赋值为2。

select * from user where username = 'one' and password = 2;

注意:setString定义为String类型就只能传String类型,也就是说定义什么类型就要传入什么类型。

重点来了

PreparedStatement的setObject的作用和setString的作用是一样的!

setObject的第一个参数是?的位置编号,第二个参数是Object类型,因为所有的类型默认继承object,这个时候参数就没有类型限制,你可以传入String类型或者Int类型…不需要手动设置传参类型。

例如:

setObject(1,"one")就是给第一个?位置上赋值为String类型的"one"。

select * from user where username = 'one' and password = ?;

setObject(2,2)就是给第二个?的位置上赋值为Int类型的2。

select * from user where username = 'one' and password = 2;

JDBC关于PreparedStatement.setObject的一些细节

JDBC中PreparedStatement.setObject(index,Object)方法,

1、index从1开始

2、在插入时间格式的字段时,此处的Object格式必须是java.sql.Date的对象

3、Oracle表中date格式可以表示年月日时分秒

4、从表中取出对象封装到JavaBean对象中,字段类型可以直接为java.util.Date 

总结