首页 > 其他 > 详细

PreparedStatement批量(batch)插入数据

时间:2016-10-10 14:00:56      阅读:127      评论:0      收藏:0      [点我收藏+]

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

 

PreparedStatement批量(batch)插入数据

原文:http://www.cnblogs.com/kuillldan/p/5945363.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!