0
0

More than 1 year has passed since last update.

Statement#exeuteBatch

Posted at

addBatchでregisterしたsqlをまとめてexecuteBatchする

public class Outer {
    public static void main(String[] args) {
        try {
        Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/data/Sample");
            try(con) {
                shokai(con);
                String sql = "insert into firsttable values (?, ?)";
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setInt(1,200);
                ps.setString(2,"one hundred");
                ps.addBatch();
                ps.setInt(1,210);
                ps.setString(2,"hundred ten");
                ps.addBatch();
                int[] ret = ps.executeBatch();
                System.out.println("insert count:" + Arrays.toString(ret));
                shokai(con);
            }
        } catch (SQLException ex ) {
            ex.printStackTrace();
        }
    }
    static void shokai(Connection con) {
        try {
            String sql = "select * from firsttable";
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(sql);
            while(rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                System.out.println(id + ":" + name);
            }
        } catch (SQLException ex ) {
            ex.printStackTrace();
        }
    }
}
10:TEN
20:TWENTY
30:THIRTY
60:sixty
50:sixty
90:AAA
110:hundred ten
insert count:[1, 1]
10:TEN
20:TWENTY
30:THIRTY
60:sixty
50:sixty
90:AAA
110:hundred ten
200:one hundred
210:hundred ten
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0