Reputation: 19
I am fetching records from table EmployeeLeave and storing it in a result set. Then I am inserting this result set in a database table but I am able to insert only the first row of the result set instead of all the rows.
How can i insert all the rows of the result set?
r = stmt.executeQuery("select * from EmployeeLeave where EmployeeNo='"+empno+"'");
while(r.next())
{
for(int i=0;i<=r.getRow();i++)
{
int empid = r.getInt(1);
String leave = r.getString(2);
r = stmt.executeQuery("insert into ApprovedLeave values('"+empid+"','"+leave+"','True')");
}
}
Upvotes: 0
Views: 581
Reputation: 159844
You cannot call executeQuery
while iterating through the ResultSet
r
. This will effectively reset your first ResultSet
as well as your Statement
, resulting in only one insert being made. To fix, create a new Statement
.
For inserting executeUpdate
should be used:
stmt2.executeUpdate("insert into ApprovedLeave values('"+empid+"','"+leave+"','True')");
Upvotes: 1
Reputation: 21
It may be because r pointing at the last row when you call the second method. Do you need to reset r before the next operation with it?
Upvotes: 0
Reputation: 30088
When you execute the inner quert for the first time, it closes the result set from the outer query, because you are re-using the same jdbc statement. For this to work, you'll need to use two different statement object instances.
However, there's really no reason to pull all of that data back to the application, just to send it back to the database. You could just do something like (syntax may vary slightly depending on database vendor):
"insert into ApprovedLeave select EmployeeNo, leave, 'True' from EmployeeLeave where EmployeeNo = '" + empno + "'"
And even better yet would be a PreparedStatement with:
"insert into ApprovedLeave select EmployeeNo, leave, 'True' from EmployeeLeave where EmployeeNo = ?"
where you then bind your empno variable to the statement
Upvotes: 1