Not using the hostname and port in jdbc url

2019-09-18 22:38发布

问题:

I have some application connecting to Oracle database through SpringJDBC as well as plain JDBC.

JDBC URL pattern is -

jdbc:oracle:thin:@hostname:portNumber/schemaName

We are trying to create a TNS entry which can be related with the application. For example if there is an application StockTrade then the schema name will be DBStockTrade.

However developers still need to know the hostname and port number for construction of JDBC URL and need to make binary change whenever the schema name is changed.

Is there a way to avoid using the hostname and port number and simply use the schema name for connecting to the database? The idea is to use some kind of property file containing the schema name only and get rid of other details.

回答1:

For the issue:

need to make binary change whenever the schema name is changed

We can simply put the JDBC URL into a configuration file

Then whenever the schema name changed, we only need to edit the configuration file and no binary change needed.

For example, save the JDBC URL to a .properties file

# config.properties

jdbc_url=jdbc:oracle:thin:@hostname:portNumber/schemaName

In the Java code:

String currentPath = this.getClass().getProtectionDomain().getCodeSource()
    .getLocation().toURI().getPath();
String configFile = currentPath + File.separator + "config.properties";
Properties prop = new Properties();
prop.load(new FileInputStream(configFile));
String jdbcUrl = prop.getProperty("jdbc_url")

So with the jdbcUrl we can connect to the database



标签: java oracle jdbc