Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get generated keys with commons dbutils?

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

like image 484
Plastic Rabbit Avatar asked Jan 02 '12 20:01

Plastic Rabbit


2 Answers

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");
like image 110
Asaph Avatar answered Sep 19 '22 04:09

Asaph


As a matter of fact I think it cannot be done with the current version of common-dbutils. A few months ago, when I was working for another company, I extented the QueryRunner with my own implementation.

The request has been submitted to the DbUtils project, and there you can even find a viable implementation which I guess you could copy if you really need it.

https://issues.apache.org/jira/browse/DBUTILS-54

like image 43
Edwin Dalorzo Avatar answered Sep 19 '22 04:09

Edwin Dalorzo