Thursday, September 16, 2010

Reading Postgres Database Connection from properties file using ResourceBundle class

DB.java

import java.sql.*;
import java.util.*;

public class DB
{
static ResourceBundle rb = ResourceBundle.getBundle("myapp", Locale.getDefault());

public static Connection getConnection ()
{
Connection conn = null;

try {
Class.forName (rb.getString("dbDriver"));
conn = DriverManager.getConnection(rb.getString("dbURL"), rb.getString("Username"), rb.getString("Password"));
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}


public static void closeConnection (Connection conn)
{

try {
if (conn !=null)
{
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
--------------------------------------------------------------------------------

CallDB.java

import java.sql.*;
import java.util.*;


public class CallDB
{
static ResourceBundle rb = ResourceBundle.getBundle("sql", Locale.getDefault());

public static void loadAndShowResultSet()
{
Connection conn = null;
Statement stmt = null;

try {
conn = DB.getConnection ();
stmt = conn.createStatement();

ResultSet rset = stmt.executeQuery(rb.getString("sql.query"));
while (rset.next())
{
System.out.println (rset.getString(1));
}

}
catch (Exception e) {
e.printStackTrace();
}
finally
{
try {
stmt.close();
DB.closeConnection (conn);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

public static void main(String args[])
{
try {
CallDB callDB= new CallDB();
callDB.loadAndShowResultSet();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

------------------------------------------------------
myapp.properties

dbDriver=org.postgresql.Driver
dbURL=jdbc:postgresql://localhost:5432/dbname
Username=postgres
Password=postgres

--------------------------------------------------------

sql.properties

sql.query=select first_name from username;

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

No comments:

Post a Comment