java - Should I close and create a new statement after every time I call execute()? -


if create statement jdbc , execute query, need close said statement , create new 1 before executing again? eclipse doesn't complain second case.

try {         connection = datasource.getconnection();          try {             statement = connection.createstatement();             statement.execute("set search_path '...'");         } {             utils.tryclose(statement);         }          try {             statement = connection.createstatement();             statement.execute("set statement_timeout " + (query_timeout_seconds * 1000));         } {             utils.tryclose(statement);         }          try {             statement = connection.createstatement();             statement.execute(query);         } {             utils.tryclose(statement);         } } {     utils.tryclose(connection); } 

as opposed to:

try {     connection = datasource.getconnection();      statement = connection.createstatement();     statement.execute("set search_path '...'");     statement.execute("set statement_timeout " + (query_timeout_seconds * 1000));     statement.execute(query); } {     utils.tryclose(statement);     utils.tryclose(connection); } 

that not required can use same statement query db multiple times, thing remember each resultset returned statement execution closed after creating new statemnet. quoting java docs:-

by default, 1 resultset object per statement object can open @ same time. therefore, if reading of 1 resultset object interleaved reading of another, each must have been generated different statement objects. execution methods in statement interface implicitly close statment's current resultset object if open 1 exists.

hence can this:-

try {      connection = datasource.getconnection();       statement = connection.createstatement();      resultset rs1=statement.execute("....");       //parse rs1      //close rs1       resultset rs2= statement.execute(....);      //parse rs1      //close rs1    } {     utils.tryclose(statement);     utils.tryclose(connection);   } 

i not sure why eclipse complaining in case of preparedstatements, whole purpose of preparedstatements define query structure , execute query multiple times changing parameters. example when want parse , insert large text file db. quoting javadocs

if want execute statement object many times, reduces execution time use preparedstatement object instead.


Popular posts from this blog