码迷,mamicode.com
首页 > 数据库 > 详细

使用jdbc向mysql批量添加几十万数据

时间:2020-02-22 09:55:27      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:bsp   oid   trace   statement   cti   image   http   imp   mil   

package com.tt.mybatis.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;

public class InsertIntoDBData {
    
    private static String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
    private static String user = "root";
    private static String password = "root";
    
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        long starTime = System.currentTimeMillis();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,password);
            //String sql1 = "insert into course(c_id,name) values (?,?)";
            //String sql2 = "insert into students(id,name) values (?,?)";
            //s_id是students表id,只有7w个数据
            //c_id是course表id,只有100个数据
            String sql3 = "insert into sc(sc_id,s_id,c_id,score) values (?,?,?,?)";
            ps = conn.prepareStatement(sql3);
            Random rand = new Random();
            for (int i = 1; i <= 700000; i++ ) {
                ps.setInt(1,i);
                ps.setInt(2,rand.nextInt(70000));
                ps.setInt(3,rand.nextInt(100));
                ps.setInt(4,rand.nextInt(100));
                ps.addBatch();
            }
            ps.executeBatch();
            long endTime = System.currentTimeMillis();
            System.out.println("OK,用时:"+ (endTime - starTime) + "毫秒");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (ps != null ) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (conn != null ) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }
            
        
    }

}
运行结果:竟然要44分钟
技术图片

 

 

 

 

使用jdbc向mysql批量添加几十万数据

标签:bsp   oid   trace   statement   cti   image   http   imp   mil   

原文地址:https://www.cnblogs.com/ttyyou/p/12344208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!