添加到批处理SQL命令声明20.15.5.Add batch SQL command into Statement

 
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值