setObject方法的作用

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

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

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

select * from user where username = ? and password = ?;
1
获取执行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 = ?;
1
setInt(2,2)就是定义参数类型为Int类型,然后给第二个?的位置上赋值为2。

select * from user where username = 'one' and password = 2;
1
注意:setString定义为String类型就只能传String类型,也就是说定义什么类型就要传入什么类型。

重点来了:
PreparedStatement的setObject的作用和setString的作用是一样的!

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

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

select * from user where username = 'one' and password = ?;
1
setObject(2,2)就是给第二个?的位置上赋值为Int类型的2。

select * from user where username = 'one' and password = 2;
原文连接:https://blog.csdn.net/m0_52991388/article/details/126803570

posted @ 2023-04-08 15:25  liangkuan  阅读(137)  评论(0)    收藏  举报