Question

I'm using the following setup:

public MySQLProcessWriter(Connection con) throws SQLException { 
 String returnNames[] = {"processId","length","vertices"};
 addresser = con.prepareStatement("INSERT INTO addressbook (length, vertices, activity) VALUES (?, ?, ?)", returnNames);
}

processId corresponds to an auto-incrementing column in the addressbook table. So the idea is: I have a repeated insert, I get back some of what was inserted + the auto-generated processId. However, I'm getting a "column not found" SQLException when I attempt to addresser.getGeneratedKeys().getInt("processId"); after executing the prepared statement (after the appropriate setting of values). The code for that is

addresser.setInt(1, length);
addresser.setInt(2, vertices);
addresser.setDouble(3, activity);
addresser.executeUpdate();
int processId = addresser.getGeneratedKeys().getInt("processId");

inside a loop that is updating length, vertices, activity. So...what gives? Am I misunderstanding what the prepareStatement(sqlstring, string[]) method does?

Was it helpful?

Solution

I think you need to call next() on the returned result set

ResultSet keys = addresser.getGeneratedKeys();
int processId = -1;
if (keys.next())
{
  processId = keys.getInt("processId");
}

OTHER TIPS

You have to call next() method on ResultSet returned from getGeneratedKeys() prior to calling getInt()

ResultSet rs = addresser.getGeneratedKeys();
int processId = 0;
if (rs.next()) {
  processId = rs.getInt("processId");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top