我是靠谱客的博主 无语棒棒糖,这篇文章主要介绍如何快速的插入 100W数据到数据库,使用PreparedStatement 最快实现!,现在分享给大家,希望可以做个参考。

有时候,我们使用数据库的时候,如何快速的添加测试数据到数据库中,做测试呢,添加100W 数据,如果使用工具的话可能很慢,这里我推荐大家使用 PreparedStatement 预编译 去进行操作:
单线程操作 ,测试 只需要 20秒 如果字段少的话,可以到几秒钟插入100w数据

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

最后

以上就是无语棒棒糖最近收集整理的关于如何快速的插入 100W数据到数据库,使用PreparedStatement 最快实现!的全部内容,更多相关如何快速的插入内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部