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

Java PreparedStatement上的SQL性能与保持打开的连接,java,mysql,sql,prepared-statement,java-6,Java,Mysql,Sql,Prepared Statement,Java 6,我正在编写一个程序,从csv文件中读取行,对于每一行,它会根据不同的数据库检查一些额外的数据,并最终将新构建的数据插入mysql数据库 BufferedReader br = new BufferedReader(new FileReader(file)); for(String line; (line = br.readLine()) != null; ) { //Read each file line try{

我正在编写一个程序,从csv文件中读取行,对于每一行,它会根据不同的数据库检查一些额外的数据,并最终将新构建的数据插入mysql数据库

        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();
生产线

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");
        }
    }
}

在寻找更好的处理SQLException的方法时,我了解了PreparedStatements的一些知识(也可以从上面的代码中获得一些帮助),在我看来,使用PreparedStatement存储mysql insert查询并在循环的每次迭代中修改参数可以使我受益匪浅。但这难道不意味着我应该在整个过程中保持与数据库的开放连接吗?这会是负面的吗?

您将分别执行每个查询。这会命中每个insert语句的数据库。相反,您应该使用语句的addBatch()方法,而不是像上面那样一个接一个地直接执行查询。添加所有查询后,应该使用语句一次性执行它们。executeBatch()方法。例如

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();

dataSource.getConnection()您是否尚未保持一个打开的连接?此呼叫看起来像单例或DIC。