当前位置:Gxlcms > 数据库问题 > jdbc实现事物管理

jdbc实现事物管理

时间:2021-07-01 10:21:17 帮助过:18人阅读

package com.transferdata;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.List;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import com.entity.Customer;

public class InsertNewSchame {

	private Connection newConn;
	public InsertNewSchame(Connection newConn){
		this.newConn = newConn;
	}
	
	
	/*
	 * 用throws Exception,而不用try/catch,目的是将异常全部抛到外层
	 */
	public boolean insertCustomer(Customer customer, String id) throws Exception{
	// account_id\mobile_app_info\zhima_score\device_token
	    String sqlInsert = "INSERT INTO adm_sys_customer(email,idcard_no,login_name,mobile_no,password,real_name) "
	    		   + "VALUES (?,?,?,?,?,?)";
	    PreparedStatement pstmt;
	   
	        pstmt = (PreparedStatement) newConn.prepareStatement(sqlInsert);
	        pstmt.setString(1, customer.getEmail());
	        pstmt.setString(2, customer.getIdcardNo());
	        pstmt.setString(3, customer.getLoginName());
	        pstmt.setString(4, customer.getMobileNo());
	        pstmt.setString(5, customer.getPassword());
	        pstmt.setString(6, customer.getRealName());
	        
	        pstmt.executeUpdate();      
	        pstmt.close();
	   
	    return true;
	    
	}
	
}

5、测试

外层捕获异常后执行回滚操作

package com.zkbc.transferdata;
import java.sql.SQLException;
import java.util.List;

import com.mysql.jdbc.Connection;
import com..entity.Customer;
public class Testtest {


        /*
	 * 外层捕获异常后执行回滚操作
	 */
	public static void main(String args[]) {
		ConnectionUtils ConnectionUtils = new ConnectionUtils();
		Connection oldConn = ConnectionUtils.getOldConn();
		Connection newConn = ConnectionUtils.getNewConn();
		
		GetOldData oldData = new GetOldData(oldConn);
		InsertNewSchame newData = new InsertNewSchame(newConn);
		try{
			oldConn.setAutoCommit(false);
			newConn.setAutoCommit(false);
			String cuId = "0";
			List<Customer> customerList = oldData.getCustomerList();
			for(Customer customer:customerList) {
				cuId = (Integer.parseInt(cuId) + 1) + "";
				//customer表和credit表
				newData.insertCustomer(customer, cuId);
			}
			
			oldConn.commit();
			newConn.commit();
		}catch(Exception e) {
			e.printStackTrace();
			try {
				oldConn.rollback();
				newConn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}finally {
			try {
				oldConn.setAutoCommit(true);
				newConn.setAutoCommit(true);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ConnectionUtils.closeConnection(oldConn);
			ConnectionUtils.closeConnection(newConn);
			
		}	
	}

}


jdbc实现事物管理

标签:jdbc   事物   

人气教程排行