发表于: 2017-12-06 23:01:22

1 677


今天完成的事:

1、测试一下连接DB中断后TryCatch是否能正常处理。

2、用事务+批量处理向数据库里插入100万条数据(约30秒)。

3、对比建索引和不建索引的效率查别。

    千万级有索引:

    无索引:



遇到的问题:

1、批量插入时一直出问题,无法达到效果

    原因缺少url参数的代码:如果没有开启rewriteBatchedStatements=true,那么就会把批量的操作当做一行行单条插入,批量操作失去意义。

rewriteBatchedStatements=true

未解决:2、一次插入100万条约30秒,但是一次1000万条执行不出来,10分钟也没有结果。

所以插入1000万的时候用了一个循环,10次100万。每次用时:

用时:34445

用时:28875

用时:23321

用时:26167

用时:22182

用时:21585

用时:27394

用时:25096

用时:32666

用时:26040




明天计划:

学习log4j查看日志。

整理spring。


收获:

1、停止mysql服务后,TryCatch扔然捕获异常信息,如下:

显示服务器连接问题;

在执行try模块时如果发生异常,则跳到Catch模块继续向下执行,try中异常行之后的不再执行。

所以无论是停止Mysql服务器,还是密码错误,提前关闭连接,都是正常的输出异常信息。

2、插入百万条数据 ,用时:34333毫秒

事务+批量提高效率,批量插入时并保证5.1.13以上版本的驱动。

PrepareStatement预编译效率更高,只编译一次。

addBatch()把sql语句装在到一起,然后一起送到数据库执行,执行需要很短时间。

代码:

public class InsertTest {
public static void main(String[] args) {
Connection conn = null;
       PreparedStatement pstm =null;
       String url = "jdbc:mysql:///test?rewriteBatchedStatements=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false";
       String user = "root";
       String password = "123456";
//        1、注册驱动
       try {
Class.forName("com.mysql.cj.jdbc.Driver");
           conn = DriverManager.getConnection(url, user, password);
           String sql = "insert into students (name,age) values (?,?)";
           pstm = conn.prepareStatement(sql);
           conn.setAutoCommit(false);
           long startTime = System.currentTimeMillis();
           Random rand = new Random();
           int a;
           for (int i=0;i<1000000;i++){
a = rand.nextInt(10);
               pstm.setString(1,"百万");
               pstm.setInt(2,a);
//                if(i%1000==0){
//                    pstm.addBatch();
//                }
//                pstm.executeUpdate();
                 pstm.addBatch();
           }
pstm.executeBatch();
           conn.commit();
           Long endTime = System.currentTimeMillis();
           System.out.println("用时:"+ (endTime-startTime));
       } catch (Exception e) {
e.printStackTrace();

       }finally {
try {
pstm.close();
           } catch (SQLException e) {
e.printStackTrace();

           }
if (conn != null){
try {
conn.close();
               } catch (SQLException e) {
e.printStackTrace();

               }
}
}
}
}

3、主键一定是唯一性索引,唯一性索引并不一定就是主键。

主键可以保证记录的唯一和主键域非空,数据库管理系统对于主键自动生成唯一索引,所以主键也是一个特殊的索引。


返回列表 返回列表
评论

    分享到