java 解析sql脚本

java执行sql脚本,一种是解析sql脚本,生成每一条sql语句,由java jdbc去执行。
第二种是利用 Ant 的SQL Task来实现执行SQL 脚本的功能。 http://daoshud1.iteye.com/blog/1913149


public static void main(String[] args) {
		try {
			List<String> sqlList = new sqlUtil().loadSql("g:\\menuinfo-sql-data.sql");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	* @Title: loadSql 
	* @Description: TODO(解析sql) 
	* @param @param sqlFile
	* @param @return
	* @param @throws Exception    设定文件 
	* @return List<String>    返回类型 
	* @throws
	 */
	private  List<String> loadSql(String sqlFile) throws Exception {
		List<String> sqlList = new ArrayList<String>();
		try {
			InputStream sqlFileIn = new FileInputStream(sqlFile);
			StringBuffer sqlSb = new StringBuffer();
			byte[] buff = new byte[1024];
			int byteRead = 0;
			while ((byteRead = sqlFileIn.read(buff)) != -1) {
				sqlSb.append(new String(buff, 0, byteRead,"utf-8"));//防止中文乱码
			}
			// Windows 下换行是 \r\n, Linux 下是 \n
			String[] sqlArr = sqlSb.toString()
					.split("(;\\s*\\r\\n)|(;\\s*\\n)");
			for (int i = 0; i < sqlArr.length; i++) {
				String sql = sqlArr[i].replaceAll("--.*", "").trim();
				if (!sql.equals("")) {
					sqlList.add(sql);
				}
			}
			return sqlList;
		} catch (Exception ex) {
			throw new Exception(ex.getMessage());
		}
	}

	/**
	 * 
	* @Title: execute 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param conn
	* @param @param sqlFile
	* @param @throws Exception    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	public void execute(Connection conn, String sqlFile){
		try {
			Statement stmt = null;
			List<String> sqlList = loadSql(sqlFile);
			stmt = conn.createStatement();
			for (String sql : sqlList) {
				stmt.addBatch(sql);
			}
			int[] rows = stmt.executeBatch();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
//			clise();
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值