开发者

JDBC, MySQL: getting back row data from PreparedStatement executes

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 attemp开发者_StackOverflowt 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?


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");
}


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");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜