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

世上唯一不能复制的是时间,唯一不能重演的是人生,唯一不劳而获的是年龄。该怎么走,过什么样的生活,全凭自己的选择和努力。人生很贵,请别浪费!与智者为伍,与良善者同行。Mybatis使用JDBC实现数据库批量添加,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

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

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!