1. public static void main(String[] args) {
    2. long start = System.currentTimeMillis();
    3. conn();
    4. long end = System.currentTimeMillis();
    5. System.out.println("耗时:" + (end - start)/1000 + "秒");
    6. }
    7. public static void conn(){
    8. //1.导入驱动jar包
    9. //2.注册驱动(mysql5之后的驱动jar包可以省略注册驱动的步骤)
    10. //Class.forName("com.mysql.jdbc.Driver");
    11. //3.获取数据库连接对象
    12. Connection conn = null;
    13. PreparedStatement pstmt = null;
    14. {
    15. try {
    16. //"&rewriteBatchedStatements=true",一次插入多条数据,只插入一次
    17. conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true","root","root");
    18. //4.定义sql语句
    19. String sql = "insert into user values(default,?,?)";
    20. //5.获取执行sql的对象PreparedStatement
    21. pstmt = conn.prepareStatement(sql);
    22. //6.不断产生sql
    23. for (int i = 0; i < 1000000; i++) {
    24. pstmt.setString(1,(int)(Math.random()*1000000)+"");
    25. pstmt.setString(2,(int)(Math.random()*1000000)+"");
    26. pstmt.addBatch();
    27. }
    28. //7.往数据库插入一次数据
    29. pstmt.executeBatch();
    30. System.out.println("添加1000000条信息成功!");
    31. } catch (SQLException e) {
    32. e.printStackTrace();
    33. } finally {
    34. //8.释放资源
    35. //避免空指针异常
    36. if(pstmt != null) {
    37. try {
    38. pstmt.close();
    39. } catch (SQLException e) {
    40. e.printStackTrace();
    41. }
    42. }
    43. if(conn != null) {
    44. try {
    45. conn.close();
    46. } catch (SQLException e) {
    47. e.printStackTrace();
    48. }
    49. }
    50. }
    51. }
    52. }