1. 程式人生 > >玩轉MySQL -----JDBC 的批處理

玩轉MySQL -----JDBC 的批處理

自動增長(只有int型可以自動增長)

除了在資料庫圖形介面設定外:

還可以在java中用這句程式碼:st.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);

statement

//獲取insert時生成的自動增長列如id
	@Test //Statement
	public void saveAutoIncrement1() throws Exception{
		Connection con = ConnUtils.getConn();
		String sql = "insert into book(name,price,birth) values('資料庫原理',32.45,'2017-07-12 18:52:12')" ;
		Statement st=con.createStatement();
		st.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
		ResultSet rs=st.getGeneratedKeys();
		if(rs.next()){
			int id = rs.getInt(1); //第一個自動增長列的資料
			System.out.println("自動增長列生成的id:"+id);
		}
		
	}

prepareStatement

@Test //PreparedStatement
	public void saveAutoIncrement2() throws Exception{
		Connection con = ConnUtils.getConn();
		String sql = "insert into book(name,price,birth) values(?,?,?)" ;
		PreparedStatement pst=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
		pst.setString(1, "軟體工程");
		pst.setDouble(2, 33.58);
		
		pst.setDate(3,new java.sql.Date( new java.util.Date().getTime() ));
		//pst.setTime(3, new Time(19, 10, 20));
		pst.executeUpdate();
		ResultSet rs=pst.getGeneratedKeys();
		while(rs.next()){
			int id=rs.getInt(1);
			System.out.println("自動增長列生成的id:"+id);
		}
	}

批處理

整個批處理只和MySQL資料庫進行一次網路通訊。若不採用批處理,

則每條sql都要有一次通訊開銷

statement:

st.addBatch(sql);//要傳入sql語句

int a[]=st.executeBatch(); //返回值是每條sql語句影響的行數

@Test //Statement
	public void batchDemo1() throws Exception{
		Connection con = ConnUtils.getConn();
		String sql_1 = "insert into book(name,price,birth) values('資料庫原理";
		String sql_2 = "',32.45,'2017-07-12 18:52:12')" ;
		Statement st = con.createStatement();
		for(int i=0;i<10;i++){
			String sql = sql_1+ (i+1) + sql_2;
			st.addBatch(sql);
		}
		
		String sql2 = "update book set price=price*1.1 where price<50";
		st.addBatch(sql2);
		
		//批處理的執行
		int a[]=st.executeBatch(); //返回值是每條sql語句影響的行數
		
		for(int k: a){
			System.out.print(k+" ");
		}
		System.out.println();
	}

PreparedStatement:

pst.addBatch(); //注意,這裡必須是空參,因為sql在pst內部封裝著呢--它是活的,通過引數設定幫我們構造的sql

pst.addBatch(sql2); //通過pst也可以新增一條寫死的sql

批處理的執行 int[] a = pst.executeBatch(); //返回值是每條sql語句影響的行數

@Test //PreparedStatement
	public void batchDemo2() throws Exception{
		Connection con = ConnUtils.getConn();
		String sql = "insert into book(name,price) values(?,?)";
		PreparedStatement pst = con.prepareStatement(sql);
		for(int i=1;i<11;i++){
			pst.setString(1, "Web開發"+i);
			pst.setDouble(2, (22+i*3) );
			pst.addBatch(); //注意,這裡必須是空參,因為sql在pst內部封裝著呢--它是活的,通過引數設定幫我們構造的sql
		}
		String sql2 = "update book set price=price*1.1 where price<50";
		pst.addBatch(sql2); //通過pst也可以新增一條寫死的sql
		
		
		//批處理的執行
		int[] a = pst.executeBatch(); //返回值是每條sql語句影響的行數
		
		for(int k: a){
			System.out.print(k+" ");
		}
		System.out.println();
	}