大家可能会遇到这样的问题,在做一个项目时需要操作数据库,需要有大量的数据需要导入到数据库中,这部分数据存到了txt文档中(可以把Word文档中的数据弄到txt文档),总不能每一条数据都复制黏贴到数据库,10k条,100k条甚至100000k条记录呢?接下来,小李帮您使用Java完成28秒导入2万条记录。
- 首先需要从文档中读取数据,这就用到了Java对文档的操作;
- 其次截取字符串,把取到的数据按照一定的规则截成自己需要的格式;
- 最后,将每一条记录插入到数据库中。
上代码:
public class Text { 2 3 private static String str; 4 5 public static void main(String[] args) throws Exception { 6 7 final String url = "jdbc:mysql://localhost:3306/edi"; 8 final String name = "com.mysql.jdbc.Driver"; 9 final String user = "root"; 10 final String password = ""; 11 Connection conn = null; 12 Class.forName(name);// 指定连接类型 13 conn = DriverManager.getConnection(url, user, password);// 获取连接 14 if (conn != null) { 15 System.out.println("获取连接成功"); 16 insert(conn); 17 } else { 18 System.out.println("获取连接失败"); 19 } 20 21 // FileReader file=new FileReader("D:\\workspace\\MyLearn\\count.txt"); 22 23 } 24 25 public static void insert(Connection conn) { 26 // 开始时间 27 Long begin = new Date().getTime(); 28 // sql前缀 29 String prefix = "INSERT INTO t_dic VALUES "; 30 try { 31 InputStreamReader inputReader = null; 32 BufferedReader bufferReader = null; 33 InputStream inputStream = new FileInputStream("G:\\贺哥\\dict1.txt"); 34 inputReader = new InputStreamReader(inputStream); 35 bufferReader = new BufferedReader(inputReader); 36 37 // 读取一行 38 String line = null; 39 StringBuffer strBuffer = new StringBuffer(); 40 41 // 保存sql后缀 42 StringBuffer suffix = new StringBuffer(); 43 // 设置事务为非自动提交 44 conn.setAutoCommit(false); 45 // 比起st,pst会更好些 46 PreparedStatement pst = (PreparedStatement) conn.prepareStatement("");// 准备执行语句 47 48 while ((line = bufferReader.readLine()) != null) { 49 suffix = new StringBuffer(); 50 strBuffer.append(str); 51 String a[] = line.split(" "); // 按照相应规则截取字符串 52 String s = ""; 53 for (int i = 1; i < a.length; i++) { 54 s += a[i] + " "; 55 } 56 String ss = s.trim(); // 去掉字符串开头和结尾的空格 57 System.out.println(a[0]); 58 System.out.println(ss); 59 60 suffix = new StringBuffer(); 61 63 // 构建SQL后缀 64 suffix.append("('" + a[0] + "','" + ss + "'),"); 65 // } 66 // 构建完整SQL 67 String sql = prefix + suffix.substring(0, suffix.length() - 1); 68 // 添加执行SQL 69 pst.addBatch(sql); 70 // 执行操作 71 pst.executeBatch(); 72 // 提交事务 73 conn.commit(); 78 79 } 80 pst.close(); 81 conn.close(); 82 83 } catch (SQLException e) { 84 e.printStackTrace(); 85 } catch (IOException e) { 86 // TODO Auto-generated catch block 87 e.printStackTrace(); 88 } 89 // 结束时间 90 Long end = new Date().getTime(); 91 // 耗时 92 System.out.println("数据插入花费时间 : " + (end - begin) / 1000 + " s"); 93 System.out.println("插入完成"); 94 } 95 }
自己尝试了上述代码,总共耗时28秒,供19885条记录。没有错误。
欢迎各位大神批评指正,相互提高!
版权所有,允许转载,转载请注明出处,侵权必究!