Hi Karen,
I don't understand what you are trying to accomplish. Can you elaborate?
A few remarks:
> stmt2 = (Statement) connection.createStatement();
No need to cast to Statement. 'stmt2' should be declared as java.sql.Statement. Same in 'stmt3' later on.
> ResultSet tableKeys = ps.getGeneratedKeys();
whats the purpose of this? Where did 'ps' come from?
> while(tableKeys.next())
> stmt3 = (Statement) connection.createStatement();
Create one statement instance per row in 'tableKeys' and assign to the same variable 'stmt3'? Why?
> if (tableKeys != null)
There's no reason for 'tableKeys' be null, ever. Statment.getGeneratedKeys() returns a ResultSet instance that may or may not contain any rows, but never null.
> stmt3.executeUpdate(sql3); // wrong
Why wrong? Perhaps you are getting a NullPointerException because 'stmt3' was never assign with a Statement instance? Note that a few lines above, 'tableKeys.next()' most probably returned 'false'.
Please carefully check your code and explain what you are trying to do. At first glance, it seems to me you should consider using AUTO_INCREMENT columns if not yet doing so (https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html,
https://dev.mysql.com/doc/refman/5.7/en/create-table.html)