JDBC、MySQL:从执行的PreparedStatement获取行数据

发布于 2024-08-09 02:46:51 字数 797 浏览 4 评论 0原文

我正在使用以下设置:

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

processId 对应于地址簿表中的自动递增列。所以想法是:我有一个重复的插入,我得到一些插入的内容+自动生成的processId。但是,当我在执行准备好的语句(在适当设置值之后)后尝试 addresser.getGenerateKeys().getInt("processId"); 时,出现“未找到列”SQLException 。其代码位于

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

更新长度、顶点、活动的循环内。那么...什么给出了?我是否误解了prepareStatement(sqlstring, string[]) 方法的作用?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

古镇旧梦 2024-08-16 02:46:51

我认为你需要对返回的结果集调用 next()

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

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");
}
清泪尽 2024-08-16 02:46:51

在调用 getInt() 之前,您必须对从 getGenerateKeys() 返回的 ResultSet 调用 next() 方法

ResultSet rs = addresser.getGeneratedKeys();
int processId = 0;
if (rs.next()) {
  processId = rs.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");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文