Java如何使用Spring JdbcTemplate向in语句中传递参数

目录

一、Jdbctemplate方式

二、NamedParameterJdbcTemplate方式

 三、总结


一、Jdbctemplate方式

传统的Jdbctemplate类无法直接向in语句传递参数,需要通过字符串拼接的方式来实现。例如:

1.常见的通过占位符查询结果方式(无法适用in语句)

//查询id等于123的用户信息
String sql = "select * from user where id = ?"; 
Map<String, Object> args = new HashMap<>();
args.put("id", 123);
jdbcTemplate.queryForList(sql, args , User.class )

2.如果使用上述方式向in语句中传递参数

//查询id为1,2,3的用户信息
String sql = "select * from user where id in (?)"; 
Map<String, Object> args = new HashMap<>();
int[] ids = {1,2,3}
args.put("id", ids);
jdbcTemplate.queryForList(sql, args , User.class ); 

    这里查询语句被替换后如下,执行时会报错

//不符合sql语句规范
select * from user where id in ([1,2,3])

3.解决方案:使用字符串拼接

String ids = "1,2,3";
String sql = "select * from user where id in (" + ids +")";

   如果入参是字符串,要用两个单引号' 内容'引起来,这样就满足SQL的语法,例如:

String ids = "'1','2','3'";
String sql = "select * from user where id in (" + ids +")";

二、NamedParameterJdbcTemplate方式

     Jdbctemplate是比较底层的类,因此功能比较有局限性。NamedParameterJdbcTemplate是对Jdbctemplate的再次封装,它可以使用具名参数来绑定Sql参数。一系列具名参数组成一个map传入,这样传参的顺序就没有限制了。

    使用NamedParameterJdbcTemplate实现in语句的传参非常简单,如下:

String sql = "select * from user where name in (:names)";
String[] arr = {"张三","李四","王五"};
ArrayList<String> names = new ArrayList<String>(Arrays.asList(arr));
Map<String, Obeject> args = new HashMap<String,Object>();
args.put("names", names);
NamedParameterJdbcTemplate jdbcTmeplate = new NameParameterJdbcTemplate(jdbctemplate);
jdbcTemplate.queryForList(sql,args);

 三、总结

使用Jdbctemplate传递给in语句参数时,如果参数是固定的,那么拼接成字符串很简单。但是如果参数不固定,是通过数组或列表给出的。那么在进行字符串拼接时,就会比较复杂麻烦,需要将数组的值转换成字符串,每个元素用逗号分隔并用单引号括起来。综合比较,给in语句传递参数推荐使用NamedParameterJdbcTemplate类来实现。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老鼠只爱大米

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值