自增长主键回显实现,批量数据插入

 1 package com.atsyc.api.preparedstatement;
 2 
 3 import org.junit.Test;
 4 
 5 import java.sql.*;
 6 
 7 public class PSOtherPart {
 8     /*
 9      * TODO:
10      *      t_user插入一条数据,并且获取数据库自增长的主键
11      *      使用总结:
12      *              1.在创建prepareStatement的时候,告知,携带回数据库增长的主键
13      *              2.获取装主键值的结果及对象,一行一列,获取对应数据
14      *
15      * TODO:
16      *      使用批量插入的形式插入一万条数据
17      *      使用总结:
18      *              1.路径后面添加?rewriteBatchedStatements=true,允许批量插入
19      *              2.insert into --- values[必须写]语句尾不能添加;结束
20      *              3.不是执行语句每条,是批量添加addBatch();
21      *              4.遍历添加完毕后,统一批量执行
22      */
23     @Test
24     public void returnPrimaryKey() throws Exception {
25         Class.forName("com.mysql.cj.jdbc.Driver");
26         Connection connection = DriverManager.getConnection("jdbc:mysql:///atsyc?rewriteBatchedStatements=true","root","Yican030615");
27         String sql = "INSERT into t_user(account,password,nickname) values (?,?,?)";
28         PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
29 
30         long start = System.currentTimeMillis();
31 
32         for(int i=0;i<10000;i++) {
33             statement.setObject(1, "test3"+i);
34             statement.setObject(2, "123333"+i);
35             statement.setObject(3, "主键获取测试员pro"+i);
36             //statement.executeUpdate();  //普通添加执行需要近十秒,下面批量添加仅需0.3秒
37             statement.addBatch();  //不执行,追击到values后面
38         }
39 
40         statement.executeBatch();  //执行批量操作
41 
42         long end = System.currentTimeMillis();
43 
44         /*
45         if(i>0){
46             System.out.println("数据插入成功!");
47             //获取回显的主键
48             //获取装主键的结果集对象 一行一列 id=值
49             ResultSet resultSet = statement.getGeneratedKeys();
50             resultSet.next();
51             int id = resultSet.getInt(1);
52             System.out.println("id = " + id);
53         }else{
54             System.out.println("数据插入失败!");
55         }
56         */
57 
58         System.out.println("执行10000次数据插入消耗的时间 = "+(end-start));
59 
60         statement.close();
61         connection.close();
62     }
63 }

 

posted @ 2024-03-06 13:29  白茶花约  阅读(61)  评论(0)    收藏  举报