简体   繁体   中英

How to get the Generated insert ID in JDBC?

My source code has the following structure:

SourceFolder
AddProduct.jsp
Source Packages
- Controller (Servlets)
SaveProduct.java
- Model (Db Operations)
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).

To insert an entry into the product_collection table i need to get generated id from product table. After that a new entry is inserted into the product_collection table.

Also, I am not using any Framework and am using Netbeans 7.3.

Problem:

A new entry is inserted into the product table with this piece of code

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

How to get the insert ID in JDBC?

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. 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)

Additionally: as javaBeginner pointed out correctly, your usage of a prepared statement is wrong. The way you do it, will still leave you wide open to SQL injection.

// 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. If you are using eg Postgres you would most probably need to pass new String[] {"product_id"}

The way you are using is not the proper way of using 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. 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

eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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