首页

关于jdbc通过Statement和PrepareStatement进行数据库批处理操作,以提供程序效率

标签:批处理,jdbc,java,Statement,PrepareStatement,sql,性能优化,OracleDriver,DriverManager,Connection     发布时间:2015-06-01   

前言

关于程序执行延时过长,很大部分来源于数据建立连接延时及连接池上限等到可用连接演示,如果能减少与数据库建立连接的次数,无疑提高了系统的执行效率,关于这一点可以将相关的频繁的sql操作以批处理的方式进行提交,以提供程序执行效率,主要有两种方式进行sql的批处理提交,一个是Statement,另外一个是PrepareStatement方式,具体如下:

一、使用Statement方式

使用Statement的executeBatch()方法执行批处理,具体代码如下:

public class statementBatchTest(){@b@@b@    public static  void main(String[] args){@b@        try{ @b@            Class.forName("oracle.jdbc.driver.OracleDriver");@b@            String url="jdbc:oracle:thin:@localhost:1521:xwood";@b@            Connection conn=DriverManager.getConnection(url,"scott","tiger");@b@            Statement stmt=conn.createStatement();@b@            stmt.addBatch("insert into sys_test values(1,2)");@b@            stmt.addBatch("update sys_test set no=3 where  id=1");@b@            stmt.addBathc("delete sys_test where no=3");@b@            stmt.executeBatch();          @b@        }catch(Exception ex){@b@            ex.printStatckTrack();@b@        }@b@    @b@    }@b@@b@}

二、使用PrepareStatement方式

使用PrepareStatement的addBatch()方法向批处理追加sql,以executeBatch方法提交批次处理,具体代码示例如下:

public class  prepareStatementBatchTest(){@b@    @b@    public static void main(String[] args){@b@        @b@        String sql="select *  from  sys_test where no=? ";@b@        try{@b@            @b@            Class.forName("oracle.jdbc.driver.OracleDriver");@b@            String url="jdbc:oracle:thin:@localhost:1521:xwood";@b@            Connection conn=DriverManager.getConnection(url,"scott","tiger");@b@            PreparedStatement ps=conn.prepareStatement(sql);@b@            ps.setString(1,"3");@b@            ps.addBatch();@b@            ps.setString(1,"4");@b@            ps.addBatch();@b@            ps.executeBatch();@b@        @b@        }catch(Exception ee){@b@            ee.printStatckTrace();@b@        }    @b@    @b@    }@b@@b@@b@}

总结

如果需要对数据进行复杂的操作,涉及多次数据变更操作,尽量放到一个批次里面进行提交处理以提供程序效率。在使用时,可以结合使用事物控制,以保证数据执行的一致完整性。