JAVA with SQL:插入命令的返回值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14234257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAVA with SQL: the return value of insert command?
提问by jeff ranz
I have a table of authors : authorID, authorName. authorID is a pk with auto increment.
我有一个作者表:authorID,authorName。authorID 是一个自动递增的 pk。
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?
我想用 java 编写一个方法,该方法从用户那里获取名称并将其添加到表中。但是我需要返回作者的 ID。有没有办法用 1 条 sql 语句做到这一点?
for example if my code has the command:
例如,如果我的代码具有以下命令:
stmt.executeUpdate("INSERT INTO authors " + "VALUES (, '"+ string.get(1) +"')");
which string.get(1) is the author name.
其中 string.get(1) 是作者姓名。
Now if i write:
现在如果我写:
ResultSet rs =stmt.executeUpdate("INSERT INTO authors " + "VALUES (, '"+ string.get(1) +"')");
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?
它说错误,因为 rs 是结果集,但返回的值是 int。这是我插入的行的 pk 吗?
回答by Evgeniy Dorofeev
try
尝试
stmt.executeUpdate("INSERT INTO authors VALUES (, '"+ string.get(1) +"')", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
long pk = rs.getLong(1);
回答by Subhrajyoti Majumder
Pass Statement.RETURN_GENERATED_KEYS while creating PreparedStatement
conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
创建时传递 Statement.RETURN_GENERATED_KEYS PreparedStatement
conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
and
PreparedStatement#getGeneratedKeys()
returns auto generated key after inert.
并
PreparedStatement#getGeneratedKeys()
在惰性后返回自动生成的密钥。
回答by PermGenError
In order to get last inserted id look at the below code:
为了获得最后插入的 id,请查看以下代码:
PreparedStatement stmnt = Conn.preparedStatement("INSERT INTO authors(col1) VALUES (?)", Statement. RETURN_GENERATED_KEYS );
stmnt.setString(col1val);
stmnt.executeUpdate();
ResultSet rs=stmnt.getGeneratedKeys();
if(rs.next()){
System.out.println(rs.getInt(1));
}
回答by Andrew
Try:
尝试:
INSERT INTO authors VALUES (...) returning authorID
When you execute it, do so with executeQuery
. You should get back a ResultSet
with one row and one column — it will be the ID.
执行时,请使用executeQuery
. 您应该返回ResultSet
带有一行和一列的 a - 这将是 ID。
回答by BigMike
I don't know if this is supported by JDBC (haven't used it in a while), but I guess you could try:
我不知道 JDBC 是否支持(有一段时间没有使用它),但我想您可以尝试:
INSERT INTO TABLE_NAME (FIELD1, FIELD2) VALUES ('foo', 'bar') RETURNING FIELD3
via executeQuery() or, if your jdbc driver doesn't support RETURNING
write a simple stored function.
通过 executeQuery() 或者,如果您的 jdbc 驱动程序不支持 RETURNING
编写简单的存储函数。
Which RDMBS are you using?
您使用的是哪个 RDMBS?