解析jdbcUrl,获取host、port、databaseName

解析jdbcUrl,获取databaseName

public class JdbcUrlUtil {
    public static String findDataBaseNameByUrl(String jdbcUrl) {
        String database = null;
        int pos, pos1;
        String connUri;

        if (StringUtils.isBlank(jdbcUrl)) {
            throw new IllegalArgumentException("Invalid JDBC url.");
        }

        jdbcUrl = jdbcUrl.toLowerCase();

        if (jdbcUrl.startsWith("jdbc:impala")) {
            jdbcUrl = jdbcUrl.replace(":impala", "");
        }

        if (!jdbcUrl.startsWith("jdbc:")
                || (pos1 = jdbcUrl.indexOf(':', 5)) == -1) {
            throw new IllegalArgumentException("Invalid JDBC url.");
        }

        connUri = jdbcUrl.substring(pos1 + 1);

        if (connUri.startsWith("//")) {
            if ((pos = connUri.indexOf('/', 2)) != -1) {
                database = connUri.substring(pos + 1);
            }
        } else {
            database = connUri;
        }

        if (database.contains("?")) {
            database = database.substring(0, database.indexOf("?"));
        }

        if (database.contains(";")) {
            database = database.substring(0, database.indexOf(";"));
        }

        if (StringUtils.isBlank(database)) {
            throw new IllegalArgumentException("Invalid JDBC url.");
        }
        return database;
    }
}

 

 

参考

 

public class JdbcUrlSplitter 
{ 
    public String driverName, host, port, database, params; 

    public JdbcUrlSplitter(String jdbcUrl) 
    { 
    int pos, pos1, pos2; 
    String connUri; 

    if(jdbcUrl == null || !jdbcUrl.startsWith("jdbc:") 
     || (pos1 = jdbcUrl.indexOf(':', 5)) == -1) 
     throw new IllegalArgumentException("Invalid JDBC url."); 

    driverName = jdbcUrl.substring(5, pos1); 
    if((pos2 = jdbcUrl.indexOf(';', pos1)) == -1) 
    { 
     connUri = jdbcUrl.substring(pos1 + 1); 
    } 
    else 
    { 
     connUri = jdbcUrl.substring(pos1 + 1, pos2); 
     params = jdbcUrl.substring(pos2 + 1); 
    } 

    if(connUri.startsWith("//")) 
    { 
     if((pos = connUri.indexOf('/', 2)) != -1) 
     { 
     host = connUri.substring(2, pos); 
     database = connUri.substring(pos + 1); 

     if((pos = host.indexOf(':')) != -1) 
     { 
      port = host.substring(pos + 1); 
      host = host.substring(0, pos); 
     } 
     } 
    } 
    else 
    { 
     database = connUri; 
    } 
    } 
} 

 

你可能感兴趣的:(java)