廖井涛
2025-11-28 67f0be5a1d634ba3274fa9366ceacc3580f056b7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.northglass.util;
 
import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.SQLException;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springside.modules.utils.PropertiesLoader;
 
public class SetupUtil {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(SetupUtil.class);
    
    /**
     * 判断数据库存在的方法。
     * 主要用在首次安装系统时,若系统中相应的数据库和表都不存在,则在页面上提示用户创建表,并且不启动监听。
     * 
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    @SuppressWarnings("unchecked")
    public static boolean databaseExists() throws ClassNotFoundException, SQLException {
        LOGGER.trace("> Start databaseExists");
        PropertiesLoader propertiesLoader = new PropertiesLoader("classpath:/application.properties");        
        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
        dataSource.setDriverClass((Class<? extends Driver>) Class.forName(propertiesLoader.getProperty("jdbc.driver")));
        dataSource.setUrl(propertiesLoader.getProperty("jdbc.url"));
        dataSource.setUsername(propertiesLoader.getProperty("jdbc.username"));
        dataSource.setPassword(propertiesLoader.getProperty("jdbc.password"));        
        
        try(Connection conn = dataSource.getConnection()){     
            ResultSet rs = conn.getMetaData().getCatalogs();
            LOGGER.trace("rs: " + rs);   
            while (rs.next()) {
                String databaseName = rs.getString(1);
                LOGGER.trace("databaseName:"+databaseName);
                if (databaseName.equalsIgnoreCase("gmms")) {
                    ResultSet tableRS = conn.getMetaData().getTables(null, "%", "%", new String[]{"TABLE"});
                    LOGGER.trace("tableRS: " + tableRS);
                    while (tableRS.next()) { 
                        String tableName = tableRS.getString(3);                    
                        if (tableName.equalsIgnoreCase("gmms_user")) {
                            return true;
                        }
                    }                
                }
            }       
            LOGGER.trace("> End databaseExists");
        }
        finally{
            
        }
       
        return false;
    }
}