good day, I hope and you can help me, what happens is that I want to recover the id inserted when I execute a function in postgresql, but the problem is that it brings a 0 since the sp runs and adds it to the view of the datatable but then I reload the page and add it to me with the maximum Id (of the inserted record), what I want more than anything is to recover that inserted id and add it to the view, this is my code where I send to call the sp:
public int guardarPelicula(moviesDTO peliculas) {
int ultimoRegistro =0;
try {
CallableStatement prcProcedimientoAlmacenado = conn.getConnection().prepareCall("{ call sp_insert_update_peliculas(?,?,?)}");
prcProcedimientoAlmacenado.setInt(1, peliculas.getId_movie());
System.out.println("Que traes 3.." + peliculas.getId_movie());
prcProcedimientoAlmacenado.setString(2, peliculas.getMovie_name());
prcProcedimientoAlmacenado.setInt(3, peliculas.getMovie_year());
System.out.println("Executando Store Procedure Insert..");
prcProcedimientoAlmacenado.execute();
System.out.println("Que traes2..." + ultimoRegistro);
return ultimoRegistro;
} catch (SQLException ex) {
Logger.getLogger(MovieDAOImplements.class.getName()).log(Level.SEVERE, null, ex);
return 0;
}
}
And this is my SP:
-- FUNCTION: public.sp_insert_update_peliculas(integer, character varying, integer)
-- DROP FUNCTION public.sp_insert_update_peliculas(integer, character varying, integer);
CREATE OR REPLACE FUNCTION public.sp_insert_update_peliculas(
out_id_movie integer,
out_nombrepelicula character varying,
out_aniopelicula integer)
RETURNS TABLE(mensaje character varying, success boolean, out_idmovies integer)
LANGUAGE 'plpgsql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
DECLARE
var_mensaje character varying;
var_success boolean;
var_max_idmovie int;
var_n integer;
BEGIN
IF(out_id_movie =0)THEN
var_max_idmovie := (SELECT COALESCE (MAX(id_movie)+1,1)
FROM cat_movies);
INSERT INTO cat_movies(
id_movie,
movie_name,
movie_year)
VALUES (var_max_idmovie,
$2,
$3);
GET DIAGNOSTICS var_n= ROW_COUNT;
GET DIAGNOSTICS var_n = ROW_COUNT;
IF(var_n>0)THEN
var_success=true;
var_mensaje='Registro agregado satisfactoriamente.';
ELSE
var_success=false;
var_mensaje='Error en el sistema favor de contactar a su administrador.';
END IF;
ELSE
UPDATE cat_movies
SET movie_name=$2,
movie_year=$3
WHERE id_movie=$1;
GET DIAGNOSTICS var_n= ROW_COUNT;
GET DIAGNOSTICS var_n = ROW_COUNT;
IF(var_n>0)THEN
var_success=true;
var_mensaje='Registro ACTUALIZADO satisfactoriamente.';
ELSE
var_success=false;
var_mensaje='Error en el sistema favor de contactar a su administrador.';
END IF;
RETURN QUERY SELECT var_mensaje,var_success, var_max_idmovie;
END IF;
END;
$BODY$;
ALTER FUNCTION public.sp_insert_update_peliculas(integer, character varying, integer)
OWNER TO postgres;
In advance, I would appreciate it if you can help me, greetings and stay tuned.