W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
HasorDB 提供提供了 5 個(gè)基于 SQL 批量操作接口,下面重點(diǎn)說(shuō)其中 4 個(gè)。另外一個(gè)會(huì)在介紹 SqlParameterSource 接口時(shí)提到
批量執(zhí)行 SQL 命令適用于不需要參數(shù)的語(yǔ)句,它們將會(huì)通過(guò) ?Statement
?接口來(lái)執(zhí)行。比如下面這個(gè)批量執(zhí)行 ?insert
?。
int[] result = jdbcTemplate.executeBatch(new String[] {
"insert into `test_user` values (11, 'david', 26, now())",
"insert into `test_user` values (12, 'kevin', 26, now())"
});
執(zhí)行結(jié)果
[1, 1]
批量執(zhí)行帶參的 SQL
String querySql = "insert into `test_user` values (?,?,?,?)";
Object[][] queryArg = new Object[][] {
new Object[] { 20, "david", 26, new Date() },
new Object[] { 22, "kevin", 26, new Date() }
};
int[] result = jdbcTemplate.executeBatch(querySql, queryArg);
執(zhí)行結(jié)果
[1, 1]
批量執(zhí)行帶參的 SQL,使用 Map 作為入?yún)?/p>
String querySql = "update test_user set name = :name where id = :id";
Map<String, Object> record1 = new HashMap<>();
record1.put("name", "jack");
record1.put("id", 1);
Map<String, Object> record2 = new HashMap<>();
record2.put("name", "steve");
record2.put("id", 2);
Map<String, Object>[] queryArg = new Map[] { record1, record2 };
int[] result = jdbcTemplate.executeBatch(querySql, queryArg);
執(zhí)行結(jié)果
[1, 1]
使用 BatchPreparedStatementSetter 接口進(jìn)行參數(shù)批量設(shè)置
String querySql = "delete from test_user where id = ?";
Object[][] queryArg = new Object[][] { new Object[] { 1 }, new Object[] { 2 } };
BatchPreparedStatementSetter batchSetter = new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setObject(1, queryArg[i][0]);
}
public int getBatchSize() {
return queryArg.length;
}
};
int[] result = jdbcTemplate.executeBatch(querySql, batchSetter);
執(zhí)行結(jié)果
[1, 1]
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: