2014-07-11 3 views
1

크기가 너무 커서 (600KB) 텍스트 파일이 있습니다.이 파일을 읽고 코드 전체를 내 데이터베이스로 보내야합니다. :오류 : 데이터 소스가 연결 설정을 거부했습니다. "연결이 너무 많습니다."

private static void readBigFileAndSendToDB() throws Exception { 
    Scanner s = new Scanner(new FileReader("tf1.txt")); 
    while (s.hasNextLine()) { 
     String eachLine = s.nextLine(); // each Line 
     sendBigFileToDB(eachLine); 
    }         // (end of file). 
    System.out.println("Sent big file to DB"); 
    s.close(); 
} 


    private static void sendBigFileToDB(String line) { 
    Connection con = null; 
    PreparedStatement ps = null; 
    String query = "Insert into BigFile(text) values ('" + line + "')"; 

    try { 
     if (line != null) { 
      con = DriverManager.getConnection(...); 
      ps = con.prepareStatement(query); 
      ps.execute(); 
     } 
    } catch (SQLException sqle) { 
     sqle.printStackTrace(); 
    } 
} 

하지만 난이 프로그램을 실행할 때,이 예외가되었습니다가 발생

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections" 
+1

당신은 완료되었습니다. –

답변

1

연결을 얻으면 연결을 닫아야합니다. 연결을 닫지 않으면 리소스 누수가 발생하며 최대 연결 수에 도달하면 결국 서버가 연결을 거부 할 수 있습니다.

난 당신이 사용의 해당 범위가 종료 될 때 try-with-resources 그렇게 자원이 자동으로 닫혀 사용하도록 코드를 변경하는 것이 좋을 것 : 나는 또한 함께 쿼리에 line 당신의 연결을 교체 한

if (line == null) return; 
String query = "Insert into BigFile(text) values (?)"; 

try (
    Connection con = con = DriverManager.getConnection(...); 
    PreparedStatement ps = con.prepareStatement(query); 
){ 
    ps.setString(1, line); 
    ps.executeUpdate(); 
} catch (SQLException sqle) { 
    sqle.printStackTrace(); 
} 

주 prepared statement 매개 변수의 적절한 사용.

코드는 속으로 연결 생성 및 문 준비를 이동하여 개선 추가 될 수 귀하의 readBigFileAndSendToDB 그래서 한 번만 수행하고 각 반복에서 오버 헤드가 발생하지 않습니다 번, 연결을 닫으십시오

String query = "Insert into BigFile(text) values (?)"; 

try (
    Scanner s = new Scanner(new FileReader("tf1.txt")); 
    Connection con = con = DriverManager.getConnection(...); 
    PreparedStatement ps = con.prepareStatement(query); 
){ 
    while (s.hasNextLine()) { 
     String line = s.nextLine(); 
     if (line == null) continue; 
     ps.setString(1, line); 
     ps.addBatch(); 
    } 
    ps.executeBatch(); 
} catch (SQLException sqle) { 
    sqle.printStackTrace(); 
} 
+0

'executeUpdate()'를'executeBatch()'로 대체 한 이유는 무엇입니까? –

+0

'resultset 객체 초기화 문'을'try()'로 옮겨야합니까? (이 질문에 있지 않다.) –

+0

@ user3808021 네, 그렇게하면 try 블록의 끝 후에 닫혀 야합니다. –

0

하십시오, 가까운 문 및 연결 종료 후 마무리 과정 :

private static void readBigFileAndSendToDB() throws Exception { 
    Scanner s = new Scanner(new FileReader("tf1.txt")); 
    while (s.hasNextLine()) { 
     String eachLine = s.nextLine(); // each Line 
     sendBigFileToDB(eachLine); 
    }         // (end of file). 
    System.out.println("Sent big file to DB"); 
    s.close(); 
} 


    private static void sendBigFileToDB(String line) { 

    PreparedStatement ps = null; 
    String query = "Insert into BigFile(text) values ('" + line + "')"; 

    try { 
     if (line != null) { 
      con = DriverManager.getConnection(...); 
      ps = con.prepareStatement(query); 
      ps.execute();    
     } 
    } catch (SQLException sqle) { 
     sqle.printStackTrace(); 
    } 
    finally { 
     if (ps != null) try { ps .close(); } catch (SQLException logOrIgnore) {} 
     if (con != null) try { con .close(); } catch (SQLException logOrIgnore) {} 
     } 
    } 
+1

리소스를 시도해 보는 것이 좋습니다. 리소스를 닫는 것이 훨씬 간단합니다. –

관련 문제