带SQL的JAVA:insert命令的返回值? [英] JAVA with SQL: the return value of insert command?

查看:545
本文介绍了带SQL的JAVA:insert命令的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作者表:authorID,authorName。
authorID是一个带有自动增量的pk。

I have a table of authors : authorID, authorName. authorID is a pk with auto increment.

我想在java中编写一个从用户获取名称并将其添加到表中的方法。但是我需要返回作者的id。有没有办法用1 sql语句做到这一点?

I'd like to write a method in java that gets a name from user and adds it to the table. however i need to return the id of the author. is there a way to do that with 1 sql statement?

例如,如果我的代码有命令:

for example if my code has the command:

stmt.executeUpdate("INSERT INTO authors " + "VALUES (, '"+ string.get(1) +"')");

其中string.get(1)是作者姓名。

which string.get(1) is the author name.

现在,如果我写:

ResultSet rs =stmt.executeUpdate("INSERT INTO authors " + "VALUES (, '"+ string.get(1) +"')");

它表示错误,因为rs是结果集,但返回的值是int。这是我插入的行的pk吗?

it says error as rs is resultset but the returned value is int. is this int the pk of the row that i have inserted?

推荐答案

试试

stmt.executeUpdate("INSERT INTO authors VALUES (, '"+ string.get(1) +"')", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
long pk = rs.getLong(1);

这篇关于带SQL的JAVA:insert命令的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆