PreparedStatement批量(batch)插入数据

JDBC操作数据库的时候,需要一次性插入大量的数据的时候,如果每次只执行一条SQL语句,效率可能会比较低。这时可以使用batch操作,每次批量执行SQL语句,调高效率。

public Boolean doCreateBatch(List<Emp> values) throws Exception
{
    try
    {
        String sql = " INSERT INTO emp(empno,ename,job,hiredate,sal,comm) VALUES "
                + " (?,?,?,?,?,?) ";
        this.conn.setAutoCommit(false);
        PreparedStatement stmt =  this.conn.prepareStatement(sql);
        for(Emp emp : values)
        {
            stmt.setInt(1, emp.getEmpno());
            stmt.setString(2, emp.getEname());
            stmt.setString(3, emp.getJob());
            stmt.setDate(4, new java.sql.Date(emp.getHiredate().getTime()));
            stmt.setDouble(5, emp.getSal());
            stmt.setDouble(6, emp.getComm());
            stmt.addBatch();
        }
        System.out.println("before executing batch...");
        stmt.executeBatch();
        this.conn.commit();
        System.out.println("after batch executed!");
        this.conn.setAutoCommit(true);
        
        return true;
    }
    catch(Exception e)
    {
        throw e; 
    }
}
原文地址:https://www.cnblogs.com/kuillldan/p/5945363.html