Reusuable class to get db details from properties file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |