Advertisement
Guest User

Untitled

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