java向數據庫批量插入數據


話不多說,代碼附上。

    // 配置文件獲取數據庫信息
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.driver-class-name}")
    private String driver;
    @Value("${spring.datasource.username}")
    private String user;
    @Value("${spring.datasource.password}")
    private String password;

 

public void batcheInsert(List<Map<String,Object>>listMap, String tableName){
        try {
            String sql = "";
            String sqlStr1 = "INSERT INTO "+tableName+" (";
            String sqlStr2=  ") VALUES (";
            String sqlStr3 = ")";
            String sqlKey = "";
            String sqlValue = "";
            for (Object key: listMap.get(0).keySet() ) {
                sqlKey+= key + ",";
                sqlValue += "?,";
            }
            sqlKey = sqlKey.substring(0,sqlKey.length() -1);
            sqlValue = sqlValue.substring(0,sqlValue.length() -1);
            sql = sqlStr1 + sqlKey + sqlStr2 + sqlValue + sqlStr3;
            logger.info("拼接的insert into SQL:" + sql);

            Connection conn = getConnection();
            conn.setAutoCommit(false);
            //構造預處理statement
            PreparedStatement pst = conn.prepareStatement(sql);
            int count = 0;
            int index = 1;
            for(int i = 1;i <= listMap.size();i++){
                for (Object val: listMap.get(i-1).values() ) {
                    pst.setString((index++),nullToNull(val));
                }
                index = 1;
                pst.addBatch();
                //每10000次提交一次
                if(i % 10000 == 0){//可以設置不同的大小;
                    ++count;
                    pst.executeBatch();
                    conn.commit();
                    pst.clearBatch();
                }
            }
            // 最后插入不足1w條的數據
            pst.executeBatch();
            conn.commit();
            logger.info("批次提交次數:" + ++count);
            pst.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

 

public Connection getConnection() {//建立返回值為Connectiong的方法
        Connection con = null;//聲明Connection對象
        try {//加載數據庫驅動類
            Class.forName(driver);
            System.out.println("數據庫驅動加載成功");
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }
        try {//通過訪問數據庫的URL獲取數據庫連接對象
            con = DriverManager.getConnection(url, user, password);
            System.out.println("數據庫連接成功");

        } catch (SQLException e) {

            e.printStackTrace();
        }
        return con;//按方法要求返回一個Connectiong對象
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM