Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

nested preparedstatement ?

Status
Not open for further replies.

WebGoat

MIS
Jul 16, 2005
85
US
nested preparedstatement ? is it possible ?

first ,i want to do a query in a table . then taking each result of that big resultset i want to insert some record into another table.


How could i do it ? is not it will be a nested ? so, i am in problem.
 
pseudo code :

Connection conn1 = new Connection();
Connection conn2;

ResultSet rs = conn1.doQuery();

while (rs.next()) {
conn2 = new Connection();
PreparedStatement ps = conn2.prepare();
ps.execute();
ps.close()
conn2.close();
}


--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
There shouldn't be any need to prepare the second statement for each insert - that kind of defeats one of the main purpose sof PreparedStatements:
Code:
// prepare both statments
PreparedStatement firstStatement = con.prepareStatement( "SELECT field1, field2 FROM some_table WHERE some_identifier=?" );
PreparedStatement secondStatement = con.prepareStatement( "INSERT INTO some_other_table VALUES(?,?)" );

// execute the SELECT query (the oneToGet variable is just an example)
int oneToGet = 10;
firstStatement.setInt( 1, oneToGet );
ResultSet rs = firstStatement.executeQuery();

// for each row retrieved
while( rs.next() ) {

   // load values into the INSERT statement and execute
   secondStatement.setInt( 1, rs.getInt( 1 ) );
   secondStatement.setString( 2, rs.getString( 2 ) );
   secondStatement.execute();
}
 
Its a much safer approach to use one statement per conn call.

All applications that use heavily db transactions should really be running through a pool. As for the statement caching, any db worth its salt will be caching statement executing plans anyway, so there is not a lot of point in "preparing" the statement in that way once off anyway.

Its better to prepare a new statement, to make sure the JDBC driver has cleaned out any globals, and let the db handle the caching IMO.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
>its a much safer approach to use one statement per conn call.
i see. i want to be safe [bigsmile]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top