JAVA JDBC 数据库的一点记录:事务

                                 JAVA JDBC 数据库的一点记录:事务



import java.sql.*;

public class TestBatch {
	
	public static void main(String[] args) throws SQLException 
	{
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
	
	
			conn = DriverManager.getConnection
			("jdbc:mysql://localhost/test","root","ZHEN");
	
		
			conn.setAutoCommit(false);
		
			////事务1  transaction
			stmt = conn.createStatement();  //执行静态 SQL 语句并返回它所生成结果的对象。 
		
			stmt.addBatch("INSERT INTO student VALUES(30,'ddd',12,'ii')");
			stmt.addBatch("INSERT INTO student VALUES(31,'ddd',12,'ii')");
			stmt.addBatch("INSERT INTO student VALUES(32,'ddd',12,'ii')");
			stmt.addBatch("INSERT INTO student VALUES(33,'ddd',12,'ii')");
		
			stmt.executeBatch();
		
		
			/////事务2
			pstmt = conn.prepareStatement("INSERT INTO student VALUES(?,?,?,?)");
		
			pstmt.setInt(1, 40);
			pstmt.setString(2,"qq");
			pstmt.setInt(3,5);
			pstmt.setString(4,"ww");
			pstmt.addBatch();
		
			pstmt.setInt(1, 41);
			pstmt.setString(2,"qq");
			pstmt.setInt(3,5);
			pstmt.setString(4,"ww");
			pstmt.addBatch();
		
			pstmt.executeBatch();
		
			///
		
			conn.commit(); 
			//若事务1 和事务2必需要同时完成 或 同时不完成,不能存在只有其中一个被完成的情况,则要用transaction
		
		}catch (ClassNotFoundException e1) {
			
			e1.printStackTrace();
		}catch (SQLException e) {
		
			e.printStackTrace();
			
			conn.rollback();  //若事务处理失则,必需回滚
			conn.setAutoCommit(true);
			
		}finally{
			stmt.close();
			pstmt.close();
			conn.close();
		}
	}

}


你可能感兴趣的:(JAVA JDBC 数据库的一点记录:事务)