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

Mic*_*Lee 29 java url parsing jdbc

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

bre*_*ttw 49

从这样的事情开始:

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

  • 你将无法从jdbc解析_some server_:oracle:thin:@ some.server:1521:XXX with the that (10认同)
  • 嗯,一般来说,JDBC URL的格式是特定于数据库的.所以没有通用的方法来解析它. (5认同)

小智 6

这对我不起作用.我提出了这些方法,基于主机名和端口始终通过冒号连接在一起的假设.这个假设适用于我在工作中处理的所有数据库(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 + "'");
}
Run Code Online (Sandbox Code Playgroud)