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

SQL performance on PreparedStatement vs keeping an open connection

我正在编写一个从 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();

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

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

您正在分别执行每个查询。这会为每个插入命中数据库 statement.Instead 你应该使用 Statement 的 addBatch() 方法,而不是像上面那样直接一个接一个地执行查询并且在添加所有查询之后应该使用 [=14= 一次执行它们]() method.e.g

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