SSM004/工作内容

一。java执行sql脚本

参考博客:java调用SQL脚本执行的方案

1.Service层代码:目的随spring容器启动即执行

//Service层代码
@Component
public class InitCfcaDB {
    final org.slf4j.Logger log = LoggerFactory.getLogger(getClass());
    @PostConstruct
    public void init(){
        log.debug("初始化表结构....");
        CfcaDbUtil.run();
    }
}
View Code

2.util工具类

package com.csvalue.utils;

import com.csvalue.common.PropertiesUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.sql.Connection;
import java.sql.DriverManager;

/*
* 初始化表结构
* */
public final class CfcaDbUtil {
    public static final String driver = PropertiesUtils.getDBProperty("jdbc.driver");
    public static final String url = PropertiesUtils.getDBProperty("jdbc.url");
    public static final String username = PropertiesUtils.getDBProperty("jdbc.username");
    public static final String userpwd = PropertiesUtils.getDBProperty("jdbc.userpwd");

    public static void run(){
        try {
            Class.forName(driver);
            //建立连接
            Connection connection=DriverManager.getConnection(url,username,userpwd);
            //创建ScriptRunner,用于执行SQL脚本
            ScriptRunner scriptRunner=new ScriptRunner(connection);
            scriptRunner.setErrorLogWriter(null);
            scriptRunner.setLogWriter(null);
            //执行sql脚本
            scriptRunner.runScript(Resources.getResourceAsReader("sql/"+"filename"+".sql"));
            connection.close();//关闭连接
            System.out.println("=====success=========");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        run();
    }
}
View Code

3.加载属性配置文件

package com.csvalue.common;

import java.util.ResourceBundle;

//加载属性配置文件
public class PropertiesUtils {

    private static ResourceBundle resource;
    private static ResourceBundle resourceDB;

    static{
        //读取配置文件 config 为文件名
        resource = ResourceBundle.getBundle("properties/config");
        resourceDB=ResourceBundle.getBundle("properties/jdbc");
    }

    /**
     * 提供外部访问的方法
     * @param key
     * @return
     */
    public static String getProperty(String key){
        //以String格式返回 key 对应的 value
        return resource.getString(key);
    }

    public static String getDBProperty(String key){
        //以String格式返回 key 对应的 value
        return resourceDB.getString(key);
    }

    public static void main(String[] args){
        //读取制定的key
        String config = PropertiesUtils.getProperty("cfca.url");
        System.out.println(config);
        String url=PropertiesUtils.getDBProperty("jdbc.url");
        System.out.println(url);
    }
}
View Code

4.属性文件jdb.properties

#数据库连接配置信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mysql
jdbc.username=root
jdbc.userpwd=shiyufeng
View Code

启动java web项目,即执行。

二。

 

posted @ 2018-12-14 15:20  kaixinyufeng  阅读(129)  评论(0编辑  收藏  举报