天天看点

JDBC处理Transaction

package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCTest {

	/**
	 * @param args
	 */
	private static final String URL="jdbc:mysql://localhost:3306/jdbc";
	private static final String DRIVER="com.mysql.jdbc.Driver";
	private static final String USER="root";
	private static final String PASSWORD="123";
	
	public static void main(String[] args) {
		Connection conn=null;
		Statement stmt=null;
		ResultSet rs=null;
		try{
			Class.forName(DRIVER);
			conn=DriverManager.getConnection(URL, USER, PASSWORD);
			conn.setAutoCommit(false);
			stmt=conn.createStatement();
			stmt.addBatch("insert into enum values(1,'a','a1');");
			stmt.addBatch("insert into enum values(2,'b','b1');");
			stmt.addBatch("insert into enum values(3,'c','c1');");
			stmt.executeBatch();
			conn.setAutoCommit(true);
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}catch(SQLException e){
			try{
				if(conn!=null) {
					conn.rollback();
					conn.setAutoCommit(true);
				}
				
			}catch(SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally {
			try{
				if(stmt!=null) {
				stmt.close();
				stmt=null;
				}
				if(conn!=null) {
					conn.close();
					conn=null;
				}
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
	}
}