NutzCN Logo
问答 nutz或者nutzboot里是否有方法初始化sql脚本?
发布于 1681天前 作者 hujun82589167 1501 次浏览 复制 上一个帖子 下一个帖子
标签:

一个nutzboot应用想在系统启动的时候执行一个sql文件,里面有建表、加数据、ddl等各种sql。
nutz或者nutzboot里有没有像springboot里
spring.datasource.schema=classpath:db/schema.sql
spring.datasource.data=classpath:db/data.sql
这种配置或者方法?

6 回复

Main方法里面 init方法 实现你想要的就可以了

@tonyyule 我的困扰不是不知道在什么地方进行数据初始化,我是想通过简单的方式执行一个sql脚本,而不是必须按照nutz标准编辑sql文件,给每条sql定义一个key,然后再setup或者mainlaunch里循环执行。
ps:你的nutzsite项目与ruoyi除了后端不一致以外,前端代码能否直接用若依的新版覆盖你项目里的前端页面?

@hujun82589167 欢迎写starter,提交贡献此功能~~

@Wizzercn starter如下,留给需要的人
配置文件有两个配置项:
nutz.dao.initsqls.path:初始化sql文件,默认db/init.sql
nutz.dao.initsqls.duplicate:是否每次重启都执行,默认true

@IocBean(
        create = "init"
)
public class InitSqlStarter {
    private static final Log log = Logs.get();
    @PropDoc(
            value = "初始化sql文件",
            defaultValue = "db/init.sql"
    )
    public static final String PROP_INITSQLS_PATH = "nutz.dao.initsqls.path";
    @PropDoc(
            value = "是否重复执行",
            defaultValue = "true",
            type = "boolean"
    )
    public static final String PROP_INITSQLS_DUPLICATE = "nutz.dao.initsqls.duplicate";
    @Inject
    protected PropertiesProxy conf;
    @Inject
    protected NutDao dao;
    public InitSqlStarter() {
    }

    public void init() {
        boolean duplicate = conf.getBoolean(PROP_INITSQLS_DUPLICATE);
        File keyfile = new File("~/initsql.key");
        if(duplicate){
            Files.deleteFile(keyfile);
        }
        if(!keyfile.exists()) {
            PreparedStatement ps = null;
            Connection conn = null;
            try {
                conn = dao.getDataSource().getConnection();
                String sql = Files.read(conf.get(PROP_INITSQLS_PATH));
                log.info("execute init db sqlfile:" + sql);
                if (sql != null && !"".equals(sql)) {
                    ps = conn.prepareStatement(sql);
                    int i = ps.executeUpdate();
                    if (i > 0) {
                        log.info("init db sqlfile done");
                        if (!duplicate) {
                            Files.createNewFile(keyfile);
                        }
                    }
                }
            } catch (Exception e) {
                log.info("error happen while executing init db sqlfile:" + e.getMessage());
            } finally {
                try {
                    if (ps != null) {
                        ps.close();
                    }
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    log.info("error happen while closing connection:" + e.getMessage());
                }
            }
        }
    }
}
添加回复
请先登陆
回到顶部