2012-02-15 18 views
22

Cómo puedo analizar una URL JDBC (oracle o sqlserver) para obtener el nombre de host, el puerto y el nombre de la base de datos. Los formatos de la URL son diferentes.Cómo analizar una URL JDBC para obtener el nombre de host, el puerto, etc.

+0

¿Qué quieres decir con que quieres analizar una URL de jdbc? Puedes usar regex. Puede dar un ejemplo – Ank

+1

jdbc: jtds: sqlserver: // nombrehost: puerto/nombrebd o jdbc: jtds: sqlserver: // nombrehost: puerto; nombrebasedatos = nombrebd o jdbc: oráculo: delgado: @nombrehost: puerto: nombrebd –

Respuesta

35

empezar con algo como esto:

 
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()); 

salida de lo anterior:

 
derby 
localhost 
1527 
/netld;collation=TERRITORY_BASED:PRIMARY 
+0

gracias ¡Mucho! Puedo obtener host, port fácilmente de esta manera, pero tengo que analizar la ruta para obtener el databasename –

+0

Sí, seguro que sí. – brettw

+8

no podrá analizar _alguno servidor_ de jdbc: oracle: thin: @ some.server: 1521: XXX con ese –

6

que no funcionó para mí. Se me ocurrieron estos métodos, basados ​​en la suposición de que el nombre de host y el puerto siempre están unidos por dos puntos. Esa suposición es válida para todas las bases de datos con las que tengo que lidiar en el trabajo (Oracle, Vertica, MySQL, etc.). Pero probablemente no funcione para algo que no llega a un puerto de red.

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 + "'"); 
} 
1

Utilizo esta clase en mis proyectos. El uso es realmente simple.

/** 
* Split di una url JDBC nei componenti. 
* Estrae i componenti di una uri JDBC del tipo: <br> 
* String url = "jdbc:derby://localhost:1527/netld;collation=TERRITORY_BASED:PRIMARY"; <br> 
* nelle rispettive variabili pubbliche. 
* @author Nicola De Nisco 
*/ 
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; 
    } 
    } 
} 
Cuestiones relacionadas