一个data patch清晰的代码模板

一. 背景:

今天公司上了一个项目, 涉及到数据的迁移,其实代码很简单,只是有些地方在以后编码过程中需要注意,写下这篇日志备忘。


二. 代码:

1. 基础代码:

public class DataPatch {
	private static Logger logger = Logger.getLogger(DataPatch.class.getName());
	
	public static void main(String[] args) {
		try {
			logger.warn("start the Job...");
			long begin = System.currentTimeMillis();
			
			DataPatch patch = new DataPatch(); 
			List<String> productList = patch.dataPrepare();
			patch.processData(productList);
			
			long end = System.currentTimeMillis();
			logger.info("<<  Total spent time: " + (end - begin) / 1000 + "s >>");  // <-- case 1
			logger.warn("end the Job...");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			System.exit(0);
		}
	}

	// prepare the patch data
	public List<String> dataPrepare() throws Exception {
		List<String> list = new ArrayList<String>();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream("/home/zdp/supplier.txt"))); // <-- case 2
		String line = null;
		while ((line = reader.readLine()) != null) {
			list.add(line.trim());
		}
		if (reader != null) {
			reader.close();
		}
		return list;
	}

	// process the business
	public void processData(List<String> list) {
		Connection conn = null;
		for (int i = 0; i < list.size(); i++) {
			String productId = null;
			try { // <-- case 3
				conn = getConnection();
				
				updateSql1(conn, productId);
				querySql(conn);  // <-- case 4
				for(...){ 
					updateSql2(conn, productId);
				}
				
				conn.commit(); // <-- case 5
				conn.close();
				logger.info("-->>  commit... ");
			} catch (Exception e) {
				logger.error("error happens: " + productId, e); // <-- case 6
				conn.rollback();
				if (conn != null) {
					conn.close();
				}
			}
		}
	}
	
	// query sql
	public Product querySql(Connection conn) throws Exception{
		...
	}
	
	// update sql 1
	public Boolean updateSql1(Connection conn, String productId) throws Exception{
		...
	}
	
	// update sql 2
	public Boolean updateSql2(Connection conn, String productId) throws Exception{
		...
	}
}
case 1. 记录时间日志

case 2. 读取数据代码
case 3. 将try catch的代码放在循环product id的里面, 当出错的时候,只把这个product id回滚
case 4. 读取数据和更新数据要使用同一个连接, 否则会读取不到更新的数据
case 5. 进入循环的时候获取数据库连接, 循环结束时提交并关闭连接, 循环完一个product id提交一次
case 6. catch异常的时候打印product id,数据库回滚, 注意要关闭连接 


你可能感兴趣的:(一个data patch清晰的代码模板)