Saturday, October 22, 2016

DB details from properties file using Java


Reusuable class to get db details from properties file.
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import helper.GetProperty;
public class ConnectToDB {
public Connection getConnection() throws ClassNotFoundException, SQLException{
String driver = null;
String url = null;
String userName = null;
String password = null;
GetProperty dbdet = new GetProperty();
driver = dbdet.getDBDetails("db_driver");
url = dbdet.getDBDetails("db_connectionurl");
userName = dbdet.getDBDetails("db_user");
password = dbdet.getDBDetails("db_password");
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userName, password);
return conn;
}
public void closeConnection(Connection conn) throws ClassNotFoundException, SQLException{
conn.close();
}
}
Now the helper function that reads from the property file and return the value from the property file.
package helper;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class GetProperty {
public String getDBDetails(String configval) {
String dbval = null;
Properties prop = new Properties();
InputStream input = null;
try {
input = GetProperty.class.getClassLoader().getResourceAsStream("resources/dbconfig.properties");
// load a properties file
prop.load(input);
// get the property value
dbval = prop.getProperty(configval, "Defaultvalue");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return dbval;
}
}