当只有一个查询要执行时,statement.executeBatch()vs statement.updateQuery()

Pau*_*aul 2 java mysql sql connection

好的,我知道Batch Processing允许将相关的SQL语句分组到一个批处理中,并通过一次调用数据库来提交它们.当您一次向数据库发送多个SQL语句时,可以减少通信开销,从而提高性能.在这种特殊情况下(见下面的代码)我认为批处理不是唯一的目的.stmt.executeBatch()添加批次后立即调用原因(?)不会stmt.executeUpdate()做同样的事情?

public void tableChanged(TableModelEvent e) {
    int row = e.getFirstRow();
    int col = e.getColumn();
    model = (MyTableModel) e.getSource();
    String stulpPav = model.getColumnName(col);
    Object data = model.getValueAt(row, col);
    Object studId = model.getValueAt(row, 0);
    System.out.println("tableChanded works");
    try {
        new ImportData(stulpPav, data, studId);
        bottomLabel.setText(textForLabel());
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    } catch (SQLException e1) {
        e1.printStackTrace();
    }
}
public class ImportData {    

    public ImportData(String a, Object b, Object c)
            throws ClassNotFoundException, SQLException {
        Statement stmt = null;
        try {
            connection = TableWithBottomLine.getConnection();
            String stulpPav = a;
            String duom = b.toString();
            String studId = c.toString();
            System.out.println(duom);
            connection.setAutoCommit(false);
            stmt = connection.createStatement();
            stmt.addBatch("update finance.fin set " + stulpPav + " = " + duom
                    + " where ID = " + studId + ";");
            stmt.executeBatch();
            connection.commit();
        } catch (BatchUpdateException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (stmt != null)
                stmt.close();
            connection.setAutoCommit(true);
            System.out.println("Data was imported to database");
        }
    }   
} 
Run Code Online (Sandbox Code Playgroud)

Mar*_*eel 5

在这种情况下,使用批处理根本没有任何优势.它甚至可能在直接引入额外开销executeUpdate(但这取决于驱动程序和数据库).

但是,不要假设批处理对所有JDBC驱动程序都有好处.我没有看过MySQL的细节,但我知道有一些JDBC驱动程序,其中内部批处理是批处理中每个语句的正常执行.

但问题中的代码有一个更大的问题:它容易受到SQL注入攻击.