Writing SQL statement with Loop Objects

Coding have never been the same!!! Some bad habits when writing codes which are redundant

String[] special = {"a1","a2","a3","a4"};  

Connection con = null;  

PreparedStatement stmt = null;  

PreparedStatement stmt2 = null;  

ResultSet rs = null;  

ResultSet rs2 = null;  

Class.forName ("com.mysql.jdbc.Driver")  

conn = DriverManager.getConnection (url, userName, password);  

String SQL_QUERY = " SELECT count(*) FROM tblABC WHERE " +
" name_tennis LIKE = ? ";  

String SQL_QUERY2 = " SELECT count(*) FROM tblABC WHERE " +
" name_swimwear LIKE = ? ";  

stmt = con.prepareStatement(SQL_QUERY);  

stmt2 = con.prepareStatement(SQL_QUERY2);  

for (int i=0;i<special[i].length;i++) {  

      stmt.setString(1,special[i]);  

      rs = stmt.executeQuery();  

      if (rs.next()) {  

         /* More work here */  

      }  

}  

for (int i=0;ii<special[i].length;i++) {  

stmt2.setString(1,special[i]);  

      rs2 = stmt2.executeQuery();  

      if (rs2.next()) {  

         /* More work here */  

      }  

}

The above is a very bad example of coding. It might work, and run smoothly but it’s really bad coding. What one should do is to not to let the code be redundant. For example, put both statements into one the loop.

for (int i=0;i<special[i].length;i++) {  

      stmt.setString(1,special[i]);  

      rs = stmt.executeQuery();  

      if (rs.next()) {  

         /* More work here */  

      }      stmt2.setString(1,special[i]);  

      rs2 = stmt2.executeQuery();  

      if (rs2.next()) {  

         /* More work here */  

      }  

}

What’s the use of this? Well, iif you have an object or rather a Bean to set into, you don’t have to loop and reloop. All can be done in the same loop. Well, hope this brings about some bad habits of coding java.

No Responses

  1. Pingback: Sample HQL Query | TechieDan January 21, 2009

Leave a Reply