发表于: 2017-09-28 18:50:26

3 693


今天完成的任务:

(1)百万条数据的插入:

测试类:

import java.sql.*;
import java.util.Date;

public class test {

public static void main(String[] args) throws ClassNotFoundException, SQLException {
final String url = "jdbc:mysql://localhost:3306/test1?characterEncoding=utf8&useSSL=false";
           final String name = "com.mysql.jdbc.Driver";
           final String user = "root";
           final String password = "0000";
           Connection conn = null;
           Class.forName(name);//指定连接类型
           conn = DriverManager.getConnection(url, user, password);//获取连接
           if (conn != null) {
System.out.println("获取连接成功");
               insert(conn);
           } else {
System.out.println("获取连接失败");
           }
}
public static void insert(Connection conn) {
// 开始时间
       Long begin = new Date().getTime();
       // sql前缀
       String prefix = "INSERT INTO student (name,age,qq) VALUES ";
       try {
// 保存sql后缀
           StringBuffer suffix = new StringBuffer();
           // 设置事务为非自动提交
           conn.setAutoCommit(false);
           // 比起st,pst会更好些
           PreparedStatement pst = (PreparedStatement) conn.prepareStatement("");//准备执行语句
           // 外层循环,总提交事务次数
           for (int i = 1; i <= 1000; i++) {
suffix = new StringBuffer();
               System.out.println("提交1000条");
               for (int j = 1; j <= 1000; j++) {
// 构建SQL后缀
                   suffix.append( "("+"'" +i+"a"+j+ "'"+"," + 800 + "," + 30 +"),");
               }


String sql = prefix + suffix.substring(0, suffix.length() - 1);
               // 添加执行SQL
               pst.addBatch(sql);
               // 执行操作
               pst.executeBatch();
               // 提交事务
               conn.commit();
               // 清空上一次添加的数据
               suffix = new StringBuffer();
           }
} catch (SQLException e) {
e.printStackTrace();
       }
Long end = new Date().getTime();
       // 耗时
       System.out.println("100万条数据插入花费时间 : " + (end - begin) / 1000 + " s");
       System.out.println("插入完成");
   }
}

控制台结果:

表格显示:

(2)完善JDBC。

测试类都通过了,还有主函数未写,明天写。


发现:以name为索引时,花费时间会多几秒,这是由于索引的作用在于提升查询的效能,但是这是以降低插入、修改、删除操作的性能为代价的。举例,在插入数据的过程中,数据引擎既要将数据写入,同时又要维护索引,可能还要判断主键重复等,对性能有一定影响。

明天的计划:整理三个版本的jdbc,根据验收要求修改,争取上交。

遇到的问题:程序爆红,通过import java.sql 和 import java.util.Date解决。

收获:学会了拼接sql插入数据的方法。

禅道:http://task.ptteng.com/zentao/task-view-10647.html 剩余六小时。


返回列表 返回列表
评论

    分享到