如何解析JDBC网址以获取主机名,端口等?

2022-09-01 01:29:14

如何解析 JDBC URL(oracle 或 sqlserver)以获取主机名、端口和数据库名称。URL 的格式是不同的。


答案 1

从下面开始:

String url = "jdbc:derby://localhost:1527/netld;collation=TERRITORY_BASED:PRIMARY";
String cleanURI = url.substring(5);

URI uri = URI.create(cleanURI);
System.out.println(uri.getScheme());
System.out.println(uri.getHost());
System.out.println(uri.getPort());
System.out.println(uri.getPath());

以上输出:

derby
localhost
1527
/netld;collation=TERRITORY_BASED:PRIMARY

答案 2

这对我来说不起作用。我提出了这些方法,基于主机名和端口总是由冒号连接在一起的假设。这个假设适用于我在工作中必须处理的所有数据库(Oracle,Vertica,MySQL等)。但它可能不适用于无法连接到网络端口的东西。

String url = null; // set elsewhere in the class
final public String regexForHostAndPort = "[.\\w]+:\\d+";
final public Pattern hostAndPortPattern = Pattern.compile(regexForHostAndPort);
public String getHostFromUrl() {
    Matcher matcher = hostAndPortPattern.matcher(url); 
    matcher.find();
    int start = matcher.start();
    int end = matcher.end();
    if(start >= 0 && end >= 0) {
        String hostAndPort = url.substring(start, end);
        String [] array = hostAndPort.split(":");
        if(array.length >= 2)
            return array[0];
    }
    throw new IllegalArgumentException("couldn't find pattern '" + regexForHostAndPort + "' in '" + url + "'");
}

public int getPortFromUrl() {
    Matcher matcher = hostAndPortPattern.matcher(url); 
    matcher.find();
    int start = matcher.start();
    int end = matcher.end();
    if(start >= 0 && end >= 0) {
        String hostAndPort = url.substring(start, end);
        String [] array = hostAndPort.split(":");
        if(array.length >= 2)
            return Integer.parseInt(array[1]);
    }
    throw new IllegalArgumentException("couldn't find pattern '" + regexForHostAndPort + "' in '" + url + "'");
}