Advertisement
Guest User

Untitled

a guest
Sep 18th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.PreparedStatement;
  8. import java.sql.SQLException;
  9.  
  10. public class InsertSql {
  11.  
  12. private String insert_sql;
  13. private String charset;
  14. private boolean debug;
  15.  
  16. private String connectStr;
  17. private String username;
  18. private String password;
  19.  
  20. public InsertSql() {
  21. connectStr = "jdbc:mysql://localhost:3306/db_ip";
  22. // connectStr +=
  23. // "?useServerPrepStmts=false&rewriteBatchedStatements=true";
  24. insert_sql = "INSERT INTO tb_ipinfos (iplong1,iplong2,ipstr1,ipstr2,ipdesc) VALUES (?,?,?,?,?)";
  25. charset = "gbk";
  26. debug = true;
  27. username = "root";
  28. password = "root";
  29. }
  30.  
  31. public void storeToDb(String srcFile) throws IOException {
  32. BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile), charset));
  33. try {
  34. doStore(bfr);
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. } finally {
  38. bfr.close();
  39. }
  40. }
  41.  
  42. private void doStore(BufferedReader bfr) throws ClassNotFoundException, SQLException, IOException {
  43. //创建MySQL驱动实例
  44. Class.forName("com.mysql.jdbc.Driver");
  45. Connection conn = DriverManager.getConnection(connectStr, username, password);
  46. conn.setAutoCommit(false);// 设置手动提交
  47. int count = 0;
  48. PreparedStatement psts = conn.prepareStatement(insert_sql);
  49. String line = null;
  50. while (null != (line = bfr.readLine())) {
  51. String[] infos = line.split(";");
  52. if (infos.length < 5)
  53. continue;
  54. if (debug) {
  55. System.out.println(line);
  56. }
  57. psts.setLong(1, Long.valueOf(infos[0]));
  58. psts.setLong(2, Long.valueOf(infos[1]));
  59. psts.setString(3, infos[2]);
  60. psts.setString(4, infos[3]);
  61. psts.setString(5, infos[4]);
  62. psts.addBatch(); // 加入批量处理
  63. count++;
  64. }
  65. psts.executeBatch(); // 执行批量处理
  66. conn.commit(); // 提交
  67. System.out.println("All down : " + count);
  68. conn.close();
  69. }
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement