读取 SQL 脚本并执行

来源:互联网 发布:linux 下except用法 编辑:程序博客网 时间:2024/06/18 11:53
package com.topway.utils;


import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
/** 
 * 读取 SQL 脚本并执行 
 * @author Unmi 
 */  
public class SqlFileExecutor {  
  
    /** 
     * 读取 SQL 文件,获取 SQL 语句 
     * @param sqlFile SQL 脚本文件 
     * @return List<sql> 返回所有 SQL 语句的 List 
     * @throws UnsupportedEncodingException 
     * @throws Exception 
     */  
public String paramString(String result) throws UnsupportedEncodingException {
result = new String(result.getBytes("ISO-8859-1"), "GBK");
return result;
}
    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*10];  
            int byteRead = 0;  
            while ((byteRead = sqlFileIn.read(buff)) != -1) {  
                sqlSb.append(new String(buff, 0, byteRead));  
            }  
  
            // 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(); 
            Pattern p = Pattern.compile("/\\*(.*?)\\*/;", Pattern.DOTALL); 
            Matcher matcher2 = p.matcher(sql); 
            sql = matcher2.replaceAll("").replaceAll("\n", "");
            p = Pattern.compile("/DEFAULT(.*?)\\,;", Pattern.DOTALL); 
            matcher2 = p.matcher(sql); 
            sql = matcher2.replaceAll(",");
            String []sqlstr=sql.split(";");
            for (String string : sqlstr) {
            string=paramString(string);
            if (!string.equals("")) {  
                         sqlList.add(string);  
                     } 
}
                
            }  
            return sqlList;  
        } catch (Exception ex) {  
            throw new Exception(ex.getMessage());  
        }  
    }   
  
    /** 
     * 传入连接来执行 SQL 脚本文件,这样可与其外的数据库操作同处一个事物中 
     * @param conn 传入数据库连接 
     * @param sqlFile SQL 脚本文件 
     * @throws Exception 
     */  
   
  
    /** 
     * 自建连接,独立事物中执行 SQL 文件 
     * @param sqlFile SQL 脚本文件 
     * @throws Exception 
     */  
    public void execute(String sqlFile) throws Exception {  
    javax.sql.DataSource ds=(javax.sql.DataSource)SpringBeanFactory.getSpringContext().getBean("dataSource");
         java.sql.Connection conn=ds.getConnection();
        Statement stmt = null;  
        List<String> sqlList = loadSql(sqlFile);  
        try {  
            conn.setAutoCommit(false);  
            stmt = conn.createStatement();  
            for (String sql : sqlList) {  
            stmt.execute(sql);
            }  
            int[] rows = stmt.executeBatch();  
            System.out.println("Row count:" + Arrays.toString(rows));  
            conn.commit();
        } catch (Exception ex) {  
        conn.rollback();  
            throw ex;  
        } finally {  
        conn.close();  
        }  
    }  
  
    public static void main(String[] args) throws Exception {  
        List<String> sqlList = new SqlFileExecutor().loadSql(args[0]);  
        System.out.println("size:" + sqlList.size());  
        for (String sql : sqlList) {  
            System.out.println(sql);  
        }  
    }  
}  
0 0
原创粉丝点击