Java – how to get the ID of automatic increment when I insert a record in the table through JDBC template

private void insertIntoMyTable (Myclass m) {
private void insertIntoMyTable (Myclass m) {
    String query = "INSERT INTO MYTABLE (NAME) VALUES (?)";
    jdbcTemplate.update(query,m.getName());
}

When the above query inserts a record, the ID column in the table will be automatically added

Is there any way to retrieve the automatically incremented ID during insertion? So in this example, the return value of my method will be int

Solution

Check this reference You can use JDBC template Update as:

Edit add import as required

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.sqlException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

The following is the code usage:

final String INSERT_sql = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
    new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws sqlException {
            PreparedStatement ps =
                connection.prepareStatement(INSERT_sql,new String[] {"id"});
            ps.setString(1,name);
            return ps;
        }
    },keyHolder);
// keyHolder.getKey() Now contains the generated key
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>