MySQL小實踐一:快速插入1000萬條數據到MySQL數據庫中

今天在網上看到一篇博文,題目是: 4分鐘插入1000萬條數據到mysql數據庫中,以爲頗有意思,就記錄下來供本身學習。
MySQL版本:mysql-5.7.22-winx64

1,設置MySQL數據庫表的容量

數據庫表的默認容量是:4M,若是存儲的數據超限的話會報錯。
在windows控制檯輸入 mysql -uroot -p,進入MySql數據庫,輸入 set global max_allowed_packet = 100*1024*1024;注意後邊的 分號

2,主要代碼

public static void main(String[] args) {
        final String driver = "com.mysql.jdbc.Driver";
        final String url = "jdbc:mysql://localhost:3306/project";
        final String user = "root";
        final String password = "253432";
        Connection conn = null;
        PreparedStatement pst =  null;
        long beginTime = 0;
        long endTime = 0;
        try {
            Class.forName(driver);//指定鏈接類型
            conn = DriverManager.getConnection(url, user, password);
            if(conn != null) {
                System.out.println("獲取鏈接成功");
                beginTime = new Date().getTime();//開始計時
                String sqlPrefix = "insert into test (id,num) values ";
                // 保存sql後綴
                StringBuffer suffix = new StringBuffer();
                // 設置事務爲非自動提交
                conn.setAutoCommit(false);
                // 比起st,pst會更好些
                pst = (PreparedStatement) conn.prepareStatement("");//準備執行語句
                // 外層循環,總提交事務次數
                for (int i = 1; i <= 100; i++) {
                    suffix = new StringBuffer();
                    // 第j次提交步長
                    for (int j = 1; j <= 100000; j++) {
                        // 構建SQL後綴
                        suffix.append("('"+ UUID.randomUUID().toString()+"','"+i*j+"'"+"),");
                    }
                    // 構建完整SQL
                    String sql = sqlPrefix + suffix.substring(0, suffix.length() - 1);
                    // 添加執行SQL
                    pst.addBatch(sql);
                    // 執行操做
                    pst.executeBatch();
                    // 提交事務
                    conn.commit();
                    // 清空上一次添加的數據
                    suffix = new StringBuffer();
                }
                endTime = new Date().getTime();//開始計時
            }else {
                System.out.println("數據庫鏈接失敗");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("com.mysql.jdbc.Driver驅動類沒有找到");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("數據庫地址錯誤");
        }finally {//釋放資源
            System.out.println("插入成功,全部時間:"+ (endTime-beginTime));
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(pst != null) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }

3,運行結果

能夠看到用了兩分鐘

clipboard.png

相關文章
相關標籤/搜索