Thursday, August 21, 2008

Get record from Table into an Array

public List getArrayList(String sql) throws WCMException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

List list = new ArrayList();
// Open Connection
try {

Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup(Global.DB_CONTEXT_NAME);
DataSource ds = (DataSource) envContext.lookup(Global.DB_RESOURCE_NAME);
conn = ds.getConnection();
ps = conn.prepareStatement(sql);
// Execute Query
rs = ps.executeQuery();

// Retrieve Record
while(rs.next()){
// Generate String array
String[] temp = new String[rs.getMetaData().getColumnCount()];
for(int i=0; i temp[i] = rs.getString(i+1);
}
list.add(temp);
}

} catch (NamingException e) {
e.printStackTrace();
throw new WCMException(e);
} catch (SQLException e) {
e.printStackTrace();
throw new WCMException(e);
}
// Close Connection
finally{
try {
if (ps != null) {
ps.close();
ps = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
throw new WCMException(e);
}

}
return list;
}

No comments: