I have to write a java program to fetch data from 3 tables. For some business reason I can not join them. I have to fetch the records one by one as follows
Fetch all records from Table1
For every record on table1 do
if some business-validation passes
retrieve corresponding records from Table2
For every record on table2 do
if some business-validation passes
retrieve corresponding records from Table3
I have written code as follows :
Statement statement1 = dbConnection.createStatement();
ResultSet rs1 = statement1.executeQuery("QUERY TO RETRIEVE DATA FROM TABLE1");
while(rs1.next()){
// Do business validation
Statement statement2 = dbConnection.createStatement();
ResultSet rs2 = statement2.executeQuery("QUERY TO RETRIEVE CORRESPONDING DATA FROM TABLE2");
while(rs2.next()){
// Do business validation
Statement statement3 = dbConnection.createStatement();
ResultSet rs3 = statement2.executeQuery("QUERY TO RETRIEVE CORRESPONDING DATA FROM TABLE3");
while(rs3.next()){
}
rs3.close();
statement3.close()
}
rs2.close();
statement2.close()
}
rs1.close();
statement1.close()
Each table can have hundreds of records. Now my questions are
Is it correct to do
createStatement
in every loop and close it ? Will it be expensive?a. What if I create 3 statements in the beginning and simply use them to call
executeQuery()
. Is it advantageous?b. In this case do I need close
statement2
&statement3
it after internal use?Which is the preferred way ? Is there any better/faster way?