import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class AddBatchSQLPreparedStatement {
public static void main(String[] args) throws Exception{
Connection con = getConnection();
con.setAutoCommit(false);
Statement st = con.createStatement();
st.executeUpdate("create table survey3(id int , name varchar(30));");
st.addBatch("Delete from survey3");
st.addBatch("insert into survey3(id,name) values(444,'ginger')");
st.addBatch("insert into survey3(id,name) values(555,'dukang')");
st.addBatch("insert into survey3(id,name) values(666,'Libai')");
int[] updateCounts = st.executeBatch();//将一批命令提交给数据库来执行,如果全部命令执行成功,则返回更新计数组成的数组。
checkUpdateCounts(updateCounts);
con.commit();
ResultSet rs = st.executeQuery("select * from survey3");
outputResultSet(rs);
rs.close();
st.close();
con.close();
}
private static void checkUpdateCounts(int[] updateCounts) {
for(int i=0; i < updateCounts.length; i++){
if(updateCounts[i] >= 0){
System.out.println("OK; updateCouts = " + updateCounts[i]);
}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");
}
}
}
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();
}
}
public static Connection getConnection() throws Exception{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/bookshop","root","");
return con;
}
}
OK; updateCouts = 0
OK; updateCouts = 1
OK; updateCouts = 1
OK; updateCouts = 1
id
name
=========
444 ginger
555 dukang
666 Libai