实现方案:
/**
* 实现: JDBC 返回插入记录的主键值
* 实现要求:前提是表的主键必须是自增长的
* @param clazz
* @param sql: INSERT INTO userinfos(userName,password,date,address) VALUES(?,?,?,?);
* @param args
* @return
*/
public static <T> Integer getGeneratedKey(Class<T> clazz, String sql, Object... args){
Integer keyValue = null;
Connection connection = JdbcUtils.getConnection();
if(null == connection){
return null;
}
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//Statement.RETURN_GENERATED_KEYS = 1
//在preparedstatement里加入statement.RETURN_GENERATED_KEYS参数,代表需要获取自增主键值
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
//在这里必须先提交修改,然后再获取主键,否则会报空指针异常
preparedStatement.executeUpdate();
resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()) {
keyValue = (Integer) resultSet.getObject(Statement.RETURN_GENERATED_KEYS);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null,preparedStatement,resultSet);
}
return keyValue;
}