I have a Statement
where I insert some values to a table in my database, this table has a primary key which is identity it's name is : numBon
.
When I execute the insert command, I want to get the value of numBon
.
for now I'm working with this code :
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT MAX(numBon) FROM BonInterne");
int numBon;
if (result.next()) {
numBon = result.getInt("numBon");
}
Isn't there any other way ?
Is this an autoincrement column? Assuming it is, you can do this:
SELECT LAST_INSERT_ID()
But that's not database agnostic. This article gives a much better answer. Or you can look at @eidsonator's comment to see a quicker snippet of how to get the ID from the insert statement.
Use Statement.getGeneratedKeys() to retrieve autogenerated values.
Statement st = connection.createStatement();
st.execute("insert into ... "); //query where the server generates a value for
//an auto incremented column
ResultSet rs = st.getGeneratedKeys
int numBon;
if (rs.next()) {
numBon = result.getInt(1);
}
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.