Recuperar ID de item salvo no banco que usa sequence

4 respostas
F

Dae galera blz?

Então o problema é o seguinte.

eu tenho um cadastro de perguntas e questoes…e é NxN(nao por mim por mim seria 1questionario X nperguntas), masss a dba não ta afim de colabora.

Ai eu preciso inserir os dados da pergunta e das questoes e depois preencher a tabela QuestionarioPergunta, com as Fk’s correspondentes de cada um deles.

Problema é, como recuperar o ID tanto de questoes como de perguntas, e dai enviar no insert para Questionarioperguntas?

Tem como recuperar o ID de um item salvo com sequence?

vlw e flw

4 Respostas

luisvix

seria isso ?

PreparedStatement pstm = connection.getConnection().prepareStatement("insert into tabela (nome) values ('luis') RETURNING id");

pstm.execute();
ResultSet rS = pstm.getResultSet();
rS.next();
int _id = rS.getInt("id");
fantomas

Se a dica anterior não funcionar tente este daqui:

stmt.executeUpdate(sQuery,Statement.RETURN_GENERATED_KEYS);

ResultSet rs = stmt.getGeneratedKeys();


flws

F

como eu faria usando isso:

public Integer save(Pergunta pergunta) {

        Map<String, Object> paramSource = new HashMap<String, Object>();
        paramSource.put("GETPERCODIGO", pergunta.getPercodigo());
        paramSource.put("GETPERTEXTO", pergunta.getPertexto());

        String sql = "";

        /* Null point exception tratar sempre assim por que deu certo
         *
         * percodigo	int2
         *pertexto	varchar
         */

        if (pergunta.getPercodigo() == null) {
            sql = "INSERT INTO public.pergunta (pertexto) VALUES (:GETPERTEXTO)  RETURNING percodigo";
        } else {
            sql = "UPDATE public.pergunta SET percodigo = :GETPERCODIGO, pertexto = :GETPERTEXTO  WHERE percodigo = :GETPERCODIGO";
        }


        return this.getSimpleJdbcTemplate().getNamedParameterJdbcOperations().update(sql, paramSource);

    }

Tentando mudando apenas o sql retorno esse problema abaixo:

type Exception report

message

descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [INSERT INTO public.pergunta (pertexto) VALUES (?) RETURNING percodigo]; SQL state []; error code [0]; Um resultado foi retornado quando nenhum era esperado.; nested exception is org.postgresql.util.PSQLException: Um resultado foi retornado quando nenhum era esperado.

root cause

org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [INSERT INTO public.pergunta (pertexto) VALUES (?) RETURNING percodigo]; SQL state []; error code [0]; Um resultado foi retornado quando nenhum era esperado.; nested exception is org.postgresql.util.PSQLException: Um resultado foi retornado quando nenhum era esperado.

root cause

org.postgresql.util.PSQLException: Um resultado foi retornado quando nenhum era esperado.

note The full stack traces of the exception and its root causes are available in the GlassFish/v3 logs.

vlw msm por enquanto

tralsl
luisvix:
seria isso ?
PreparedStatement pstm = connection.getConnection().prepareStatement("insert into tabela (nome) values ('luis') RETURNING id");

pstm.execute();
ResultSet rS = pstm.getResultSet();
rS.next();
int _id = rS.getInt("id");

creio que funcione se trocar por:

PreparedStatement pstm = connection.getConnection().prepareStatement("insert into tabela (nome) values ('luis') RETURNING id");
ResultSet rs = pstm.executeQuery();
rs.next();
int _id = rs.getInt("id");
Criado 4 de junho de 2009
Ultima resposta 3 de set. de 2009
Respostas 4
Participantes 4