欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java使用Spring JdbcTemplate向in語句中傳遞參數(shù)的教程詳解

 更新時間:2023年07月05日 11:22:55   作者:老鼠只愛大米  
這篇文章主要給大家介紹Java如何使用Spring JdbcTemplate向in語句中傳遞參數(shù),文中有詳細的流程步驟和代碼示例,需要的朋友可以參考下

一、Jdbctemplate方式

傳統(tǒng)的Jdbctemplate類無法直接向in語句傳遞參數(shù),需要通過字符串拼接的方式來實現(xiàn)。例如:

1.常見的通過占位符查詢結(jié)果方式(無法適用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語句中傳遞參數(shù)

//查詢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 ); 

這里查詢語句被替換后如下,執(zhí)行時會報錯

//不符合sql語句規(guī)范
select * from user where id in ([1,2,3])

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

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

如果入?yún)⑹亲址脙蓚€單引號' 內(nèi)容'引起來,這樣就滿足SQL的語法,例如:

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

二、NamedParameterJdbcTemplate方式

Jdbctemplate是比較底層的類,因此功能比較有局限性。NamedParameterJdbcTemplate是對Jdbctemplate的再次封裝,它可以使用具名參數(shù)來綁定Sql參數(shù)。一系列具名參數(shù)組成一個map傳入,這樣傳參的順序就沒有限制了。

使用NamedParameterJdbcTemplate實現(xiàn)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);

三、總結(jié)

使用Jdbctemplate傳遞給in語句參數(shù)時,如果參數(shù)是固定的,那么拼接成字符串很簡單。但是如果參數(shù)不固定,是通過數(shù)組或列表給出的。那么在進行字符串拼接時,就會比較復(fù)雜麻煩,需要將數(shù)組的值轉(zhuǎn)換成字符串,每個元素用逗號分隔并用單引號括起來。綜合比較,給in語句傳遞參數(shù)推薦使用NamedParameterJdbcTemplate類來實現(xiàn)。

到此這篇關(guān)于Java使用Spring JdbcTemplate向in語句中傳遞參數(shù)的教程詳解的文章就介紹到這了,更多相關(guān)Java Spring JdbcTemplate傳遞參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論