Search code examples
javajdbcapache-commonsapache-commons-dbutils

How to get generated keys with commons dbutils?


I don't understand how to get auto generated keys with commons-dbutils?


Solution

  • You can use QueryRunner#insert(). Below is an example. Given a table called users, which has an auto generated primary key column and a varchar column called username, you can do something like this:

    DataSource dataSource = ... // however your app normally gets a DataSource 
    QueryRunner queryRunner = new QueryRunner(dataSource);
    String sql = "insert into users (username) values (?)";
    long userId = queryRunner.insert(sql, new ScalarHandler<Long>(), "test");