• 周日. 5月 26th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

spring使用mybatis执行SQL脚本,创建和初始化数据库

admin

11月 28, 2021
package com.sy.ai.context;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


@Component
@Log4j2
public class ApplicationContextHelper implements ApplicationContextAware {

//    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException {
        try {
            javax.sql.DataSource dataSource =
                (javax.sql.DataSource) applicationContext.getBean("dataSource");
            java.sql.Connection connection = dataSource.getConnection();
            Statement st = connection.createStatement();
            String sql = "select count(*) from pg_tables where schemaname = 'public';";
            ResultSet rs = st.executeQuery(sql);
            if (rs.next()) {
                if (rs.getInt(1) == 0) {
                    log.info("database not inited; then init database");

                    ScriptRunner runner = new ScriptRunner(connection);
                    runner.setStopOnError(true);
                    log.info(System.getProperty("user.dir"));
                    try {
                        runner.runScript(new InputStreamReader(
                            this.getClass().getResourceAsStream("/sql/public.sql"),
                            "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    connection.commit();
                    connection.close();
                    log.info("execute sql file success");
                } else {
                    log.info("table ip_camera exists");
                }
            }
            connection.close();
        } catch (SQLException e1) {
            e1.printStackTrace();
            // System.exit(0);
        }
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注