PreparedStatement上的SQL性能与保持开放连接

问题描述:

我正在写一个程序,它读取csv文件中的行,它针对每个这些行检查其他数据库中的其他数据,并最终将新构建的数据插入到一个MySQL数据库。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"); 
     } 
    } 
} 

我已经学到了一些东西有关的PreparedStatement时,我一直在寻找一种更好的方式来处理的SQLException(也可以得到一些帮助,上面的代码),并且在我可以看到它,我可以从使用PreparedStatement存储mysql插入查询中获益,并且只需在循环的每次迭代中修改参数即可。但是,这不意味着我应该在整个过程中保持与数据库的开放连接吗?这会以任何方式消极吗?

+0

'dataSource.getConnection();'你还没有保持一个打开的连接吗?这个调用看起来像单身或DIC。 – bassxzero

您正在分别执行每个查询。这会针对每个插入语句触发数据库。相反,您应该使用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();