简体   繁体   English

如何在JDBC中获取生成的插入ID?

[英]How to get the Generated insert ID in JDBC?

My source code has the following structure: 我的源代码具有以下结构:

SourceFolder 资料夹
AddProduct.jsp AddProduct.jsp
Source Packages 源码包
- Controller (Servlets) - 控制器 (Servlet)
SaveProduct.java SaveProduct.java
- Model (Db Operations) - 模型 (DB操作)
ProductDbOperations.java ProductDbOperations.java

I am inserting a new product into the product table and at the same time I am inserting an entry into product_collection table (product_id | collection_id). 我将新产品插入产品表,同时将条目插入product_collection表(product_id | collection_id)。

To insert an entry into the product_collection table i need to get generated id from product table. 要将条目插入到product_collection表中,我需要从product表中获取生成的ID。 After that a new entry is inserted into the product_collection table. 之后,将新条目插入到product_collection表中。

Also, I am not using any Framework and am using Netbeans 7.3. 另外,我没有使用任何框架,而是在使用Netbeans 7.3。

Problem: 问题:

A new entry is inserted into the product table with this piece of code 这段代码将新条目插入到产品表中

IN: ProductDbOperations.java IN:ProductDbOperations.java

try
{
    this.initConnection(); // Db connection 
    pst = cn.prepareStatement("INSERT INTO product values('"+name+"', "+quantity+", "+price+")");
    rs = pst.executeUpdate();
}
catch(SQLException ex)
{   

}

I Also used the solution at following link which doesn't works for me. 我还在下面的链接上使用了该解决方案,该链接对我不起作用。 I didn't got any SQL exception 我没有任何SQL异常

How to get the insert ID in JDBC? 如何在JDBC中获取插入ID?

so help me find out why this code not working for me . 因此,请帮助我找出为什么此代码对我不起作用。 Thanks a million. 太感谢了。

Not all drivers support the version of getGeneratedKeys() as shown in the linked answer. 并非所有驱动程序都支持getGeneratedKeys()的版本,如链接的答案所示。 But when preparing the statement, you can also pass the list of columns that should be returned instead of the "flag" Statement.RETURN_GENERATED_KEYS (and passing the column names works more reliably in my experience) 但是,在准备语句时,您也可以传递应返回的列列表,而不是传递“ flag” Statement.RETURN_GENERATED_KEYS (根据我的经验,传递列名的方法会更可靠)

Additionally: as javaBeginner pointed out correctly, your usage of a prepared statement is wrong. 另外:正如javaBeginner正确指出的那样,您对准备好的语句的使用是错误的。 The way you do it, will still leave you wide open to SQL injection. 您这样做的方式仍将使您对SQL注入持开放态度。

// run the INSERT
String sql = "INSERT INTO product values(?,?,?)";
pst = cn.prepareStatement(sql, new String[] {"PRODUCT_ID"} );
pst.setString(1, name);
pst.setInt(2, quantity);
pst.setInt(3, price);
pst.executeUpdate();

// now get the ID:
ResultSet rs = pst.getGeneratedKeys();
if (rs.next()) {
   long productId = rs.getLong(1);
}

Note that the column name passed to the call is case-sensitive. 请注意,传递给调用的列名区分大小写。 For Oracle the column names are usually uppercase. 对于Oracle,列名通常为大写。 If you are using eg Postgres you would most probably need to pass new String[] {"product_id"} 如果使用的是Postgres,则很可能需要传递new String[] {"product_id"}

The way you are using is not the proper way of using preparedstatement 您使用的方式不是使用PreparedStatement的正确方式

use the following way 使用以下方式

    pst = cn.prepareStatement("INSERT INTO product values(?,?,?)");
pst.setString(1,name);
pst.setInt(2,quantity);
pst.setInt(3,price);
pst.executeUpdate();

Yes there is a way to retrieve the key inserted by SQL. 是的,有一种方法可以检索SQL插入的密钥。 You can do it by: Using Statement.RETURN_GENERATED_KEYS in your previous insert and get the key which can be used in further insert 您可以执行以下操作:在先前的插入中使用Statement.RETURN_GENERATED_KEYS并获取可在以后的插入中使用的密钥

eg: 例如:

String query = "INSERT INTO Table (Col2, Col3) VALUES ('S', 50)";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM