日期:2014-05-16 浏览次数:20748 次
@Test public void testInsertFollowRelation(){ String db = "com.mysql.jdbc.Driver"; String host = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=GBK"; String user = "abc"; String passwd = "abc"; Connection con = null; try{ Class.forName(db).newInstance(); } catch (Exception e) { System.out.println("加载驱动失败:" + db); } long starTime = System.currentTimeMillis(); try { long startRowNum = 0; long count = 0; //使用事务插入,每10000条数据提交一下事务。 //提高效率 for(int i = 0; i < 10; i++){ BufferedReader reader = new BufferedReader(new FileReader(new File("E:\\test.txt"))); con = DriverManager.getConnection(host, user, passwd); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("INSERT INTO test " + "(id,info) " + "VALUES(?,?,?,now())"); String info = null; while((info= reader.readLine()) != null){ pstmt.setLong(1, startRowNum); pstmt.setLong(2, info); pstmt.executeUpdate(); count++; startRowNum ++; if(startRowNum % 10000 == 0){//如果数据条数达到10000条,则提交事务 con.commit(); con.close(); //重开链接 con = DriverManager.getConnection(host, user, passwd); con.setAutoCommit(false); pstmt = con.prepareStatement("INSERT INTO test " + "(id,info) " + "VALUES(?,?,?,now())"); System.out.println("数据量达到10000条,提交事务完成。"); } } reader.close(); } long endTime = System.currentTimeMillis(); System.out.println("共耗时:<" + new Float(((endTime-starTime)/1000)) + ">秒。插入了(" + count + ")条数据"); } catch(Exception e){ e.printStackTrace(); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } }