String sql = "insert into usr (email, usr, pwd) values (?, ?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = null;
ps.setString(1, usr.getEmail());
ps.setString(2, usr.getUsr());
ps.setString(3, usr.getPwd());
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
usr.setId(rs.getInt(1));
}
ps.close();
UserResult userResult = new UserResult();
userResult.setSuccess(true);
userResult.setUsr(usr);
return userResult;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
应该很简单吧,大家都能看懂的,只试了mysql可以,不知其他的数据库行不行
参考: 《Is ther a way to retrieve the autoincrement ID from a prepared statement》