Writing SQL statement with Loop Objects

70 / 100 SEO Score

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

Code Loop

Here are some Code with Loop Objects

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++) {<special.length;i++)></special.length;i++)>  

     stmt.setString(1,special[i]);  
     rs = stmt.executeQuery();  
     if (rs.next()) {  

         /* More work here */  
     }  

}  

for (int i=0;i<special.length;i++)></special.length;i++)>i<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.

Better Code in Loop Objects

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, if you have an object or rather a Bean to set into, you don’t have to loop and redo the loop. All this can be done in the same loop. Well, hope this brings about some bad habits of coding java.

Added: 2022-07-21

Now there are so many changes to Java, there are newer ways to write a For Loop or loops. Have a look at one for Java 5 which was written back in 2009. Java has evolved over the years.

No Responses

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

Leave a Reply