Java基础之批量产生脚本

     最近业务需要在表上面添加几个字段,用于是按月分表的,预计要提供3年共36各表的修改脚本,本人想偷点懒,写了个简单的Java,一次生成,源码如下,我就不一一解释了,主要思路是替换字符串,很简单。

    

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class 批量产生脚本 {
	public static void main(String[] args) throws Exception {
		String baseStr = readFileContent("f:/saveFile/模版.sql", "utf-8");
		String tmpStr=null;
		List<String> monthsList = getEveryMonth("2011-01-01", "2015-01-01", "");
		StringBuffer result=new StringBuffer(5120);
		for (String str : monthsList) {
			tmpStr=baseStr.replaceAll("#yyyymm#", str);
			result.append(tmpStr).append("\r\n");
		}
		writeStrToFile(result.toString(),"f:/saveFile/处理结果.sql","utf-8");
	}

	public static void writeStrToFile(String str, String filePath,
			String charsetName) throws Exception {
		if (charsetName == null) {
			charsetName = "utf-8";
		}
		File file1 = new File(filePath);
		OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(
				file1), charsetName);
		out.write(str);
		out.close();
	}

	public static String readFileContent(String fileName, String charsetName)
			throws Exception {
		if (charsetName == null) {
			charsetName = "utf-8";
		}
		File file = new File(fileName);
		if (!file.exists() || file.isDirectory()) {
			return null;
		}
		InputStreamReader read = new InputStreamReader(
				new FileInputStream(file), charsetName);// 考虑到编码格式
		StringBuffer result = new StringBuffer((int) file.length());
		BufferedReader bufferedReader = new BufferedReader(read);
		String lineTxt = null;
		while ((lineTxt = bufferedReader.readLine()) != null) {
			result.append(lineTxt).append("\r\n");
		}
		return result.toString();
	}

	public static List<String> getEveryMonth(String beginDateStr,
			String endDateStr, String split) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date beginDate = null, endDate = null;
		try {
			beginDate = format.parse(beginDateStr);
			endDate = format.parse(endDateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(endDate);
		int endYear = c.get(Calendar.YEAR);
		int endMonth = c.get(Calendar.MONTH) + 1;
		c.setTime(beginDate);
		int startYear = c.get(Calendar.YEAR);
		int startMonth = c.get(Calendar.MONTH) + 1;
		int totalM = 12 * (endYear - startYear) + endMonth - startMonth;
		List<String> everyMonths = new ArrayList<String>();
		String tmpStr = formatYear(startYear) + split
				+ formatMonthDay(startMonth);
		everyMonths.add(tmpStr);
		for (int i = 0; i < totalM; i++) {
			startMonth = startMonth + 1;
			if (startMonth > 12) {
				startMonth = 1;
				startYear += 1;
			}
			tmpStr = formatYear(startYear) + split + formatMonthDay(startMonth);
			everyMonths.add(tmpStr);
		}
		return everyMonths;
	}

	public static String formatMonthDay(int decimal) {
		DecimalFormat df = new DecimalFormat("00");
		return df.format(decimal);
	}

	public static String formatYear(int decimal) {
		DecimalFormat df = new DecimalFormat("0000");
		return df.format(decimal);
	}

}

    如想得到2个日期内的每一天,可以看下:

    http://bbs.ibeifeng.com/simple/index.php?t14118.html

    代码我也拿过来了,如下:

   

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * From:http://bbs.ibeifeng.com/simple/index.php?t14118.html
 * 
 * @author Administrator
 * 
 */
public class GetEveryDayHelper {
	public static void main(String[] args) {
		List<String> list = GetEveryDayHelper.getEveryday("2014-01-01",
				"2014-03-02", "_");
		for (String result : list) {
			System.out.println(result);
		}
	}

	/** 闰年中每月天数 */
	private static final int[] DAYS_P_MONTH_LY = { 31, 29, 31, 30, 31, 30, 31,
			31, 30, 31, 30, 31 };

	/** 非闰年中每月天数 */
	private static final int[] DAYS_P_MONTH_CY = { 31, 28, 31, 30, 31, 30, 31,
			31, 30, 31, 30, 31 };

	/** 代表数组里的年、月、日 */
	private static final int Y = 0, M = 1, D = 2;

	/**
	 * 将代表日期的字符串分割为代表年月日的整形数组
	 * 
	 * @param date
	 * @return
	 */
	public static int[] splitYMD(String date) {
		date = date.replace("-", "");
		int[] ymd = { 0, 0, 0 };
		ymd[Y] = Integer.parseInt(date.substring(0, 4));
		ymd[M] = Integer.parseInt(date.substring(4, 6));
		ymd[D] = Integer.parseInt(date.substring(6, 8));
		return ymd;
	}

	/**
	 * 检查传入的参数代表的年份是否为闰年
	 * 
	 * @param year
	 * @return
	 */
	public static boolean isLeapYear(int year) {
		return ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)));
	}

	/**
	 * 日期加1天
	 * 
	 * @param year
	 * @param month
	 * @param day
	 * @return
	 */
	private static int[] addOneDay(int year, int month, int day) {
		if (isLeapYear(year)) {
			day++;
			if (day > DAYS_P_MONTH_LY[month - 1]) {
				month++;
				if (month > 12) {
					year++;
					month = 1;
				}
				day = 1;
			}
		} else {
			day++;
			if (day > DAYS_P_MONTH_CY[month - 1]) {
				month++;
				if (month > 12) {
					year++;
					month = 1;
				}
				day = 1;
			}
		}
		int[] ymd = { year, month, day };
		return ymd;
	}

	/**
	 * 将不足两位的月份或日期补足为两位
	 * 
	 * @param decimal
	 * @return
	 */
	public static String formatMonthDay(int decimal) {
		DecimalFormat df = new DecimalFormat("00");
		return df.format(decimal);
	}

	/**
	 * 将不足四位的年份补足为四位
	 * 
	 * @param decimal
	 * @return
	 */
	public static String formatYear(int decimal) {
		DecimalFormat df = new DecimalFormat("0000");
		return df.format(decimal);
	}

	/**
	 * 计算两个日期之间相隔的天数
	 * 
	 * @param begin
	 * @param end
	 * @return
	 * @throws ParseException
	 */
	public static long countDay(String begin, String end) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date beginDate, endDate;
		long day = 0;
		try {
			beginDate = format.parse(begin);
			endDate = format.parse(end);
			day = (endDate.getTime() - beginDate.getTime())
					/ (24 * 60 * 60 * 1000);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return day;
	}

	/**
	 * 以循环的方式计算日期
	 * 
	 * @param beginDate
	 *            endDate
	 * @param days
	 * @return
	 */
	public static List<String> getEveryday(String beginDate, String endDate,
			String split) {
		long days = countDay(beginDate, endDate);
		int[] ymd = splitYMD(beginDate);
		List<String> everyDays = new ArrayList<String>();
		everyDays.add(beginDate);
		for (int i = 0; i < days; i++) {
			ymd = addOneDay(ymd[Y], ymd[M], ymd[D]);
			everyDays.add(formatYear(ymd[Y]) + split + formatMonthDay(ymd[M])
					+ split + formatMonthDay(ymd[D]));
		}
		return everyDays;
	}

}

    全文完。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一、简介 1.1前言 1、由于最近工作一直用Oracle,故对Oracle数据库研究为对象。 2、根据工作业务需求实际情况进行功能研发。为什么要开发呢?因为在数据库升级或者迁移的时候,为了保证不同环境不同数据库数据保持同步,故数据库SQL脚本非常作用。比如:数据库主脚本,副脚本,增量脚本。 3、 什么是主脚本、副脚本、增量脚本呢? 3.1、主脚本指数据库表或存储过程,视图脚本,序列等脚本。 3.2、副脚本指必须执行主脚本之后才执行的脚本。换句话说在没执行主键脚本的情况下,副脚本执行之后会回滚事务失败。 3.3、增量脚本指在执行主脚本或副脚本之后,根据需求对某个表添加/修改约束(主外键约束,长度约束等),添加/修改字段/添加数据等情况对数据库结构改变处理的一种行为脚本。 1.2作用 1、 快速产出自定义规则需要的SQL脚本。 2、减少人工编写SQL脚本出错率问题,完全通过程序检测SQL准确性。 3、帮助开发人员提高SQL编写效率,减少人工编写SQL开发成本问题。 4、帮助开发人员节约时间,同时避免繁琐不必要编写SQL的工作。 二、实现方式与原理 2.1实现方式 1、实现方式分:正向与逆向实现。什么是正向与逆行呢【是否有鸡还是有蛋,先后道理同等】 2、正向方式:首先把设计好数据库表文档,把所有表的字段属性配置到EXCEL或者CSV格式的文件通过JXL/POI技术去读取文件的字段,再通过其他技术一系列程序处理之后生成所需要的SQL脚本。 3、逆向方式:首先有数据库表,然后通过ORM持久化技术连接数据库再读取表的字段等属性出来,再通过其他技术一系列程序处理之后生成所需要的SQL脚本。 2.2原理 对数据库软件内置核心表或视图查询出来存储用户行为表结构所有属性信息,对此属性结构信息进行分析与组装所需要SQL脚本
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值