views:

152

answers:

2

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?

A: 

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");
}
ChssPly76
+1  A: 

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");
}
delux247
well.. I guess I wasn't first... looks like we are both probably correct then.
delux247