the right way of programming

If you see the example belong, is that the right way to program?

What do I mean exactly. Can I give a db-connection as parameter to another method? Can I give a list to another void methode and fill it there?

public List getTestList(){

Connection dbconn = session.connection();

ArrayList list =new ArrayList();

try{

String sql ="some select sql statement";

PreparedStatement pstmt = dbconn.prepareStatement(sql);

ResultSet rs = pstmt.executeQuery(sql);

while (rs.next()){

getSubTestList(rs, list, dbconn);

}

pstmt.close();

rs.close();

}catch (SQLException ex){

log.error("Blablabla");

log.error(ex);

}

return list;

}

privatevoid getSubTestList(ResultSet rs, ArrayList list, Connection dbconn){

String sql2 =null;

PreparedStatement pstmt2 =null;

ResultSet rs2 =null;

try{

String test = rs.getString(1);

String test2 =null;

while (test !=null){

sql2 ="some other select sql statement";

pstmt2 = dbconn.prepareStatement(sql2);

rs2 = pstmt2.executeQuery(sql2);

while (rs2.next()){

test2 = rs2.getString(1);

list.add(test2);

}

}

rs2.close();

pstmt2.close();

}catch (SQLException ex){

log.error("Blablabla");

log.error(ex);

}

}

[2529 byte] By [bartdepauw] at [2007-11-26 12:17:21]
# 1
Looks okay to me, at a first glance. I wouldn't call it getList but fillList to make clear you're manipulating the list, but that's all.By the way, please also close the connection in the first method, and do all the closing in a finally block.
CeciNEstPasUnProgrammeur at 2007-7-7 14:54:44 > top of Java-index,Archived Forums,Socket Programming...
# 2
sometimes one sql may suffice or use a stored procedure
mchan0 at 2007-7-7 14:54:45 > top of Java-index,Archived Forums,Socket Programming...
# 3

My personal preferences for architecture differ a bit, though it seems appropriate. What I find bad is the following:

sql2 = "some other select sql statement";

pstmt2 = dbconn.prepareStatement(sql2);

rs2 = pstmt2.executeQuery(sql2);

For each loop, you create a new prepared statement and explicitly close only the last one (after the loop). Creating a statement for each iteration is not necessary. Even more, you don't use the advantage of a prepared statement to a "normal" statement, i.e. you should create a prepared statement using a query placeholder and set this placeholder to the value of "test" in each loop, then just call executeQuery() without parameter.

quitte at 2007-7-7 14:54:45 > top of Java-index,Archived Forums,Socket Programming...