import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class CheckBatchUpdateException {
public static void main(String[] args) throws Exception{
Connection con = getConnection();
con.setAutoCommit(false);
Statement st = con.createStatement();
st.executeUpdate("create table survey4(id int, name varchar(30));");
String INSERT_RECORD = "insert into survey4(id, name) values(?,?)";
PreparedStatement psmt = con.prepareStatement(INSERT_RECORD);
psmt.setString(1, "1");
psmt.setString(2, "name1");
psmt.addBatch();
psmt.setString(1, "2");
psmt.setString(2, "name2");
psmt.addBatch();
try{
int[] updateCounts = psmt.executeBatch();
}catch(BatchUpdateException e){
int[] updateCounts = e.getUpdateCounts();
checkUpdateCounts(updateCounts);
try{
con.rollback();
}catch(Exception e2){
e.printStackTrace();
System.exit(1);
}
}
con.commit();
ResultSet rs = st.executeQuery("select * from survey4");
outputResultSet(rs);
rs.close();
st.close();
con.close();
}
private static void outputResultSet(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfCount = rsmd.getColumnCount();
for(int i = 1; i < numberOfCount + 1; i ++){
String columnName = rsmd.getColumnName(i);
System.out.println(columnName +" ");
}
System.out.println();
System.out.println("===============");
while(rs.next()){
for(int i = 1; i < numberOfCount + 1; i++){
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
}
private static void checkUpdateCounts(int[] updateCounts) {
for(int i = 0; i < updateCounts.length; i ++){
if(updateCounts[i] >= 0){
System.out.println("OK; updateCounts = " + Statement.SUCCESS_NO_INFO);
}else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
System.out.println("OK; updateCount=Statement.SUCCESS_NO_INFO");
} else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
System.out.println("Failure; updateCount=Statement.EXECUTE_FAILED");
}
}
}
public static Connection getConnection() throws ClassNotFoundException, SQLException{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/bookshop","root","");
return con;
}
}
id
name
===============
1 name1
2 name2