Properties file are very useful in case of passing some parameter which are frequently used in a normal java application.
Like DB configuration. Details regarding DB Configuration can be saved in Properties file and loaded/deployed along with application itself
In this example i am using Ubuntu12.04 machine with MySql DB and Eclipse Juno IDE
The main class file and .properties file are both saved in the same package
Like DB configuration. Details regarding DB Configuration can be saved in Properties file and loaded/deployed along with application itself
In this example i am using Ubuntu12.04 machine with MySql DB and Eclipse Juno IDE
The main class file and .properties file are both saved in the same package
class LoadProptiesTest
{
public static void main(String args[])
{
try
{
loadProp();
}
catch (SQLException ex)
{
for (Throwable t : ex)
t.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public static void loadProp() throws SQLException, IOException
{
Connection conn = getConnection();
try {
Statement stat = conn.createStatement();
stat.executeUpdate("CREATE TABLE FAMILY(NAME CHAR(20))");
stat.executeUpdate("INSERT INTO FAMILY VALUES('SARAH')");
stat.executeUpdate("INSERT INTO FAMILY VALUES('JOHN')");
ResultSet result = stat.executeQuery("SELECT * FROM FAMILY");
for(int x = 1; x <= 4; x++){
if(result.absolute(x)){
System.out.println("" + x + ": "+ result.getString(1));
}
}
result.close();
}finally{
conn.close();
}
}//end of loadProp
public static Connection getConnection()
throws SQLException, IOException
{
//i am creating Properties instance
Properties props = new Properties();
//now i am loading DB.properties file,
//by getting stream of it from classloader
props.load(TestDB.class.getClassLoader()
.getResourceAsStream("DB.properties"));
//Here i am getting the values from DB.properties file
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
/*finally getting Connection*/
return DriverManager.getConnection(url, username, password);
}
}
0 comments:
Post a Comment