Reputation: 4542
Hi all following is my database connection file,
package org.slingemp.common;
import java.sql.Connection;
import java.sql.DriverManager;
public class JDBCManager {
public Connection mysqlConnection() {
Connection dbConnection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
dbConnection=DriverManager.getConnection("jdbc:mysql://localhost:3306/slingemp","root","root");
//System.out.println("mysql Driver Connedted::::::::");
} catch (Exception e) {
e.printStackTrace();
}
return dbConnection;
}
}
in this i want to make connection string and driver name configurable. how to do this and where to put the file which contains configurable values?
Regards Tony
Upvotes: 0
Views: 1030
Reputation: 20323
You can place these values in a properties file say database.properties
file, then load those properties by using a code like below:
private void loadProperties(){
InputStream inputStream = JDBCManager.class.getClassLoader().getResourceAsStream("database.properties");
try {
databaseProperties.load(inputStream); // database properties is an instance variable Properties databaseProperties;
} catch (IOException e) {
logger.error("Exception occurred while loading server properties", e);
}
}
As per comments:
Yes, JNDI can be used in Tomcat, for configuring datasource on Tomcat 7 please read this official documentation
Upvotes: 2
Reputation: 23413
You can put them into .properties
file or server JNDI resources.
jdbc.properties example:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/yourDatabaseName
jdbc.username=username
jdbc.password=password
Then in java class use this to get properties:
public static ResourceBundle getJdbcBundle() {
return ResourceBundle.getBundle("jdbc");
}
String url = SomeClass.getJdbcBundle().getString("jdbc.url");
But more efficient way would be to use JNDI.
Upvotes: 1