2017-10-19 14 views
-1

CSV 파일에서 행을 읽는 프로그램을 작성합니다. 각 행마다 추가 데이터에 대해 다른 데이터베이스를 검사하고 마지막으로 새로 생성 된 데이터를 MySQL DB. 나는 더 나은되는 SQLException을 처리하는 방법 (또한 약간의 도움을받을 수 위의 코드) 그리고, 찾고 때PreparedStatement에서의 SQL 성능 대 개방 연결 유지

 BufferedReader br = new BufferedReader(new FileReader(file)); 
     for(String line; (line = br.readLine()) != null;) { //Read each file line 
      try{ 
       processLine(line); 
      } catch(ProcessLineException e){ 
       logger.warn("Something happened"); 
      } 
     } 
     br.close(); 

processLine는

private void processLine(String line) throws ProcessLineException{ 
    ... 
    insertData(foo, data); 
} 

private void insertData(String foo, String data) { 
    Connection connection = null; 
    PreparedStatement pStatement = null; 
    try{ 
     connection = dataSource.getConnection(); 
     pStatement = connection.prepareStatement("INSERT INTO table VALUES(?,?)"); 
     pStatement.setString(1, foo); 
     pStatement.setString(2, data); 
    } catch(SQLException e){ 
     logger.error("Error when inserting data"); 
    } finally { 
     try { 
      pStatement.close(); 
      connection.close(); 
     } catch (SQLException e) { 
      logger.warn("Couldn't close resources"); 
     } 
    } 
} 

나는자는 PreparedStatements에 대해 몇 가지를 배웠다되고 나는 그것을보고, PreparedStatement를 사용하여 mysql 삽입 쿼리를 저장하고 루프의 각 반복에서 매개 변수를 수정함으로써 이익을 얻을 수있다. 그렇다고해서 전체 과정에서 데이터베이스와의 연결을 유지해야한다는 것을 의미하지는 않습니까? 그것은 어떤면에서 부정적인 것이겠습니까?

+0

'dataSource.getConnection();'아직 열려있는 단일 연결을 유지하고 있지 않습니까? 이 호출은 싱글 톤 또는 DIC처럼 보입니다. – bassxzero

답변

1

각 쿼리는 별도로 실행됩니다. 이것은 각 insert 문에 대해 데이터베이스를 조회합니다. 대신 위의 쿼리를 하나씩 직접 실행하는 대신 Statement의 addBatch() 메서드를 사용해야하며 모든 쿼리를 추가 한 후에 statement.executeBatch() 메서드를 사용하여 한 번에 실행해야합니다. .eg

import java.sql.Connection; 
import java.sql.Statement; 

//... 

Connection connection = new getConnection(); 
Statement statement = connection.createStatement(); 

for (Employee employee: employees) { 
    String query = "insert into employee (name, city) values('" 
      + employee.getName() + "','" + employee.getCity + "')"; 
    statement.addBatch(query); 
} 
statement.executeBatch(); 
statement.close(); 
connection.close();