java jdbc向数据库插入大量数据

Java代码   收藏代码
  1. public class Main {   
  2. public static void main(String[] args) throws Exception{   
  3. String sql = "insert into mobile_place(number,place) values(?,?)";   
  4. int count = 0;//计数器   
  5. Connection conn = JDBCUtil.getConnection();   
  6. PreparedStatement pstmt = conn.prepareStatement(sql);   
  7. try {   
  8. InputStreamReader is = new InputStreamReader(new FileInputStream(new File("D:/CC.txt")),"utf-8");   
  9. BufferedReader br = new BufferedReader(is);   
  10. while(br.readLine() != null){   
  11. conn.setAutoCommit(false);//设置数据手动提交,自己管理事务   
  12. count++;//没读取一行数据,计数器+1   
  13. String str = br.readLine().toString().trim();//读取一行数据   
  14. String s1 = str.substring(0, str.indexOf(","));//取逗号以前的一段   
  15. String s2 = str.substring(str.indexOf(",")+1,str.length());//取逗号之后的一段   
  16. pstmt.setString(1, s1);   
  17. pstmt.setString(2, s2);   
  18. pstmt.addBatch();//用PreparedStatement的批量处理   
  19.   
  20. if(count%500==0){//当增加了500个批处理的时候再提交   
  21. pstmt.executeBatch();//执行批处理   
  22. conn.commit();//提交   
  23. conn.close();//关闭数据库   
  24. conn = JDBCUtil.getConnection();//重新获取一次连接   
  25. conn.setAutoCommit(false);   
  26. pstmt = conn.prepareStatement(sql);   
  27. }   
  28. System.out.println("已插入"+count+"条数据");   
  29. }   
  30. if(count%500!=0){//while循环外的判断,为了防止上面判断后剩下最后少于500条的数据没有被插入到数据库   
  31. pstmt.executeBatch();   
  32. conn.commit();   
  33. }   
  34. pstmt.close();   
  35. conn.close();   
  36. catch (Exception e) {   
  37. e.printStackTrace();   
  38. }   
  39. }   
  40. }   
  41. 500可以自己增大,执行效率很高。比单挑执行再插入快多了   
  42.   
  43. getConnection()为获取数据库连接   
  44. public static Connection getConnection(){   
  45. try {   
  46. Class.forName("com.mysql.jdbc.Driver");   
  47. catch (ClassNotFoundException e) {   
  48. e.printStackTrace();   
  49. }   
  50. try {   
  51. conn = DriverManager.getConnection(url, userName, password);   
  52. catch (SQLException e) {   
  53. e.printStackTrace();   
  54. }   
  55. return conn;   
  56. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值