jdbc的批处理实现

来源:互联网 发布:海隆软件待遇好吗 编辑:程序博客网 时间:2024/05/21 22:53

jdbc的批处理实现

  1. 对于preparedStatement预处理执行sql语句的时候(这种情况是针对同一条sql语句被多次执行)
    举例如下
package day10.wyn;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Arrays;import org.junit.Test;import util.wyn.MyDBUtils;public class Batch {    private Connection con=null;    private PreparedStatement pstmt=null;    private ResultSet rs=null;    @Test    public void  groupD() throws SQLException{        con=MyDBUtils.getCon();        String sql="insert into user(username,password) values (?,?)";        pstmt=con.prepareStatement(sql);        for(int i=1;i<500;i++){            pstmt.setString(1, "wang"+i);            pstmt.setString(2, "123456");            pstmt.addBatch();        }            int [] result=pstmt.executeBatch();            System.out.println(Arrays.toString(result));            MyDBUtils.getClose(con, pstmt, rs);    }}

2 . 对于Statement执行sql语句的时候(这种情况针对执行不同的sql语句)
举例如下

package day10.wyn;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Arrays;import org.junit.Test;import util.wyn.MyDBUtils;public class Batch {    private Connection con=null;    private PreparedStatement pstmt=null;    private ResultSet rs=null;    @Test    public void  groupD1() throws SQLException{        Statement stmt=null;        String a="huang";        String b="guo";        con=MyDBUtils.getCon();        String sql1="insert into user(username,password) values ('"+a+"','"+b+"');";        String sql2="insert into user(username,password) values ('"+a+"','"+b+"')";        stmt=con.createStatement();        stmt.addBatch(sql1);        stmt.addBatch(sql2);            int [] result=stmt.executeBatch();            System.out.println(Arrays.toString(result));            MyDBUtils.getClose(con, pstmt, rs);    }}
0 0
原创粉丝点击