HasorDB 批量操作SQL

2021-12-30 11:07 更新

HasorDB 提供提供了 5 個(gè)基于 SQL 批量操作接口,下面重點(diǎn)說(shuō)其中 4 個(gè)。另外一個(gè)會(huì)在介紹 SqlParameterSource 接口時(shí)提到

批量執(zhí)行 SQL 命令?

批量執(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]

參數(shù)化 SQL 批量執(zhí)行?

批量執(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]

Map數(shù)組作為批量參數(shù)?

批量執(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?

使用 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]


以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)