Mybatis使用JDBC实现数据库批量添加

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());
        }
    }

posted @ 2024-03-19 16:29  sowler  阅读(27)  评论(0编辑  收藏  举报