欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

jdbc批量数据插入的代码,jdbc批量插入,1899942 ,一

来源: javaer 分享于  点击 41598 次 点评:86

jdbc批量数据插入的代码,jdbc批量插入,1899942 ,一


1899942 ,一    1899944 ,二  1899946 ,三 1899948 ,四  1899950 ,五    1899952 ,六    1899954 ,和  1899956 ,在 1899958 ,的  1899960 ,对 1899962 ,需 1899964 ,大规模  1899966 ,压力 1899968 ,大城市 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 有几万条这样的数据需要插入数据库 public class Main { public static void main(String[] args) throws Exception{ String sql = "insert into mobile_place(number,place) values(?,?)"; int count = 0;//计数器 Connection conn = JDBCUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); try { InputStreamReader is = new InputStreamReader(new FileInputStream(new File("D:/CC.txt")),"utf-8"); BufferedReader br = new BufferedReader(is); while(br.readLine() != null){ conn.setAutoCommit(false);//设置数据手动提交,自己管理事务 count++;//没读取一行数据,计数器+1 String str = br.readLine().toString().trim();//读取一行数据 String s1 = str.substring(0, str.indexOf(","));//取逗号以前的一段 String s2 = str.substring(str.indexOf(",")+1,str.length());//取逗号之后的一段 pstmt.setString(1, s1); pstmt.setString(2, s2); pstmt.addBatch();//用PreparedStatement的批量处理 if(count%500==0){//当增加了500个批处理的时候再提交 pstmt.executeBatch();//执行批处理 conn.commit();//提交 conn.close();//关闭数据库 conn = JDBCUtil.getConnection();//重新获取一次连接 conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql); } System.out.println("已插入"+count+"条数据"); } if(count%500!=0){//while循环外的判断,为了防止上面判断后剩下最后少于500条的数据没有被插入到数据库 pstmt.executeBatch(); conn.commit(); } pstmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } 500可以自己增大,执行效率很高。比单挑执行再插入快多了 getConnection()为获取数据库连接 public static Connection getConnection(){ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { conn = DriverManager.getConnection(url, userName, password); } catch (SQLException e) { e.printStackTrace(); } return conn; }
相关栏目:

用户点评