jdbc事务回滚 批量操作数据 一个例子

一个例子

//jdbc 事务回滚 批量操作数据
public int addProductInfo(BankCreditProductInfo creditInfo) {
	int result = 0;	//定义返回值
	int insertId=0; //定义获取最后插入记录的自增id值
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	try {
		String sql = "INSERT INTO table1 (name,pass) values(?,?)";
		conn = DBConnection.getBankConnection();
		conn.setAutoCommit(false);
		pstmt = conn.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
		pstmt.setString(1, "1");
		pstmt.setString(2, "2");
		result = pstmt.executeUpdate();
		rs = pstmt.getGeneratedKeys();   //获取最后插入记录的自增id值
		if(null != rs && rs.next()) {
			insertId = rs.getInt(1);
			result = rs.getInt(1);
		}
		//批量插入数据   例下 插入3条数据
		sql =  "INSERT INTO table2(nameid,kinds) values(?,?)";
		pstmt = conn.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
		String kindsString = "1,2,3,";
		for(String type :  creditInfo.getCity_id_attr().split(",")){
			  pstmt.setInt(1, insertId);
			  pstmt.setInt(2, 1);
			  pstmt.addBatch();
		}
		pstmt.executeBatch();
		conn.commit();//手动提交
		return result;
	} catch(Exception e) {
		try {
			conn.rollback(); //回滚
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
			e.printStackTrace();
		return 0;
	} finally {
		try {
			if(pstmt != null)pstmt.close();
			if(conn != null)conn.close();
			if(rs != null)rs.close();
		} catch (Exception e2) {
			e2.printStackTrace();
		}
	}
}


你可能感兴趣的:(JavaSE)