Search code examples
javasqloracle-databaseauto-increment

not all variables bound when returning inserted id Oracle


I'm trying to get the new id when inserted new data in database table, but I got:

ORA-01008: not all variables bound

I'm doing it from a Java SE project,

 public ResultSet ejecutarConsulta(String instruccionSql){
        rs = null;
        try {
                st = con.createStatement();
                rs = st.executeQuery(instruccionSql);
                System.out.println("Consulta Exitosa");
        } catch (SQLException e) {
                System.out.println("Error en la Consulta: "+e.getMessage());
        }
        return rs;
    }

And the String "instruccionSql" that i'm passing is

     insert  into Usuario(DOCUMENTOIDENTIDAD,NOMBRE,CARGO,CONTRASENA,PERMISO)
 values ('22323','asfa','Administrador','123456','0')
 RETURNING ID INTO :temp

I have the corresponding trigger and Seq to generate the table autoincrement id.


Solution

  • Use CallableStatement and register the OUT parameter.
    This is an excellent opportunity to register the IN parameters too.

    String mySql = "DECLARE x NUMBER; BEGIN "
            + "  insert  into Usuario(DOCUMENTOIDENTIDAD,NOMBRE,CARGO,CONTRASENA,PERMISO) "
            + "  values (?,?,?,?,?) "
            + "  RETURNING ID INTO x;"
            + "  ? := x;"
            + "END; ";
    CallableStatement cal = conn.prepareCall(mySql);
    
    cal.setString(1, "22323");
    cal.setString(2, "asfa");
    cal.setString(3, "Administrador");
    cal.setString(4, "123456");
    cal.setString(5, "0");
    cal.registerOutParameter(6, java.sql.Types.INTEGER);
    
    cal.executeQuery();
    
    Integer newId = cal.getInt(6);