1、spring注入数据源
@Resource(name = "dataSource")
private DataSource dataSource;
2、连接数据库批量添加
public void insertJdbc(List<StatisticStatus> statusList) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = dataSource.getConnection();
connection.setAutoCommit(false);
String sql = "INSERT INTO statistic_status " +
"(building_name, floor_name, device_id, optime, duration_time, last_optime) " +
"VALUES " +
"(?, ?, ?, ?, ?, ?)";
statement = connection.prepareStatement(sql);
for (StatisticStatus status : statusList) {
statement.setString(1, status.getBuildingName());
statement.setString(2, status.getFloorName());
statement.setString(3, status.getDeviceId());
statement.setTimestamp(4, new java.sql.Timestamp(status.getOptime().getTime())); //不能使用Date类型进行添加,sql.Date只能显示日期,不能显示时间。
statement.setString(5, doorlockStatus.getDurationTime());
statement.setTimestamp(6, new java.sql.Timestamp(status.getLastOptime().getTime()));
statement.addBatch();
}
statement.executeBatch();
connection.commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
statement.close();
connection.close();
}
}
3、编写批量添加方法以供调用
private void saveBatch(List<StatisticStatus> statusList){
if (CollectionUtils.isEmpty(statusList)){
return;
}
try {
insertJdbc(statusList);
}catch (Exception e){
log.error("saveBatch insertJdbc error : {}",e.getMessage());
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/260219.html