java 代码初始化数据库表结构,存储过程和函数的方法

package xxx;

import java.io.File;
import java.util.Map;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.types.FileSet;
import org.framework.config.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;




public class JdbcUtils {
    private final static Logger logger = LoggerFactory.getLogger(JdbcUtils.class);
    /**刷新数据库脚本,存入数据库中
     * @param path
     * j2ee web path: this.getClass().getClassLoader().getResource("/").getPath();
     * j2se path:new File(JdbcUtils.class.getResource("/").getFile()).getCanonicalPath();
     * thread path:Thread.currentThread().getContextClassLoader().getResource("").toString().replaceFirst("file:/", "");
     */
    public static void  scanSQL(String... paths){
        try{
            Map jdbcMap = Global.getJDBCInfo();
            //jdbc配置信息不存在 不执行
            if(jdbcMap==null){
                return ;
            }
            String path = "";
            if(paths==null||paths.length<=0){
                path = Thread.currentThread().getContextClassLoader().getResource("").toString().replaceFirst("file:/", "");
            }else{
                path = paths[0];
            }
            String driver = jdbcMap.get("driver").toString();
            String url = jdbcMap.get("url").toString();
            String user = jdbcMap.get("user").toString();
            String psd = jdbcMap.get("psd").toString();
            SQLExec sqlExec = new SQLExec();
            sqlExec.setDriver(driver);
            sqlExec.setUrl(url);
            sqlExec.setUserid(user);
            sqlExec.setPassword(psd);
            //结束符为/ 表、函数、存储过程都要以/结尾
            sqlExec.setDelimiter("/");
            //设置脚本路径
            FileSet fileSet=new FileSet();
            fileSet.setProject(new Project());
            fileSet.setDir(new File(path+Global.getDBShellPath()));
            //只处理以sql结尾的文件
            fileSet.setIncludes("*.sql");
            sqlExec.addFileset(fileSet);
            //有出错的语句该如何处理
            sqlExec.setOnerror((SQLExec.OnError)(EnumeratedAttribute.getInstance(SQLExec.OnError.class, "abort")));
            sqlExec.setPrint(true); //设置是否输出
            sqlExec.setProject(new Project()); // 要指定这个属性,不然会出错
            sqlExec.execute();
        }catch(Exception e){
            logger.info("scanSQL error",e);
        }
    }
    public static void main(String args[]){
        //scanSQL();
        String path;
        try {
            //path = new File(JdbcUtils.class.getResource("/").getFile()).getCanonicalPath();
            //path = Thread.currentThread().getContextClassLoader().getResource("").toString().replaceFirst("file:/", "");
            scanSQL();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

猜你喜欢

转载自blog.csdn.net/boenwan/article/details/73368673