Skip to content
Advertisement

Is insert.addBatch() accessible outside of this for loop?

I have multiple for loops where I am setting the values to be inserted into a MySQL DB.
My question is will insert.addBatch(); detect the insert values if it is outside of the for loop. Below is an example:

List<String> lstUser = usageEvent.getUserName();
List<String> lstFullName = usageEvent.getFullName();
List<String> lstUserType = usageEvent.getUserType();

for(String userName : lstUser) {
            insert.setString(1, userName);
        }
for(String fullName : lstFullName) {
            insert.setString(2, fullName);
        }
for(String userType : lstUserType) {
            insert.setString(3, userType);
        }
insert.addBatch();

Edit: Added extra code above to show that I am casting from a list to a string to obtain the values. I am not sure if this will change the approach to the question.

Advertisement

Answer

If you use Iterators, this inserts as much records as possible

Iterator<String> iUserName = idvEUserName.iterator();
Iterator<String> iFullName = idvEFullName.iterator();
Iterator<String> iUserType = idvEUserType.iterator();

while(iUserName.hasNext() && iFullName.hasNext() && iUserType.hasNext()) {
    insert.setString(1, iUserName.next());
    insert.setString(2, iFullName.next());
    insert.setString(3, iUserType.next());
    insert.addBatch(); 
}
insert.executeUpdate();
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement