简体   繁体   English

SQL查询的返回方法

[英]Return method of a sql query

Good afternoon guys, I created a query for the return of sql but I can not change the return to return it Next, I can return return the query inside the method but if I want to pick the method to add a combobox or to work with the returned value I can not only return it inside the method. 下午好,我为sql的返回创建了查询,但是我无法更改返回的返回值。接下来,我可以在方法内部返回return的查询,但是如果我想选择方法来添加组合框或使用该方法返回值我不仅可以在方法内部返回它。

How can I change this method to use a return? 如何更改此方法以使用退货?

private void onClickLocalizarCidadePorEstado() throws Exception {
        CidEstController cc = new CidEstController();
        try {
            List<Cidade> c = cc.buscaCidadePorEstado(uf);
            for(Cidade cidade : c)
                System.out.println(cidade.getNom_cidade());
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Ocorreu um erro, tente novamente!n" +
                            e.getLocalizedMessage()
                    );
        } catch (NullPointerException e){
            JOptionPane.showMessageDialog(this, "Contato n&atilde;o localizdo ou n&atilde;o existe!n" + 
                            e.getLocalizedMessage()
                    );
        }
    }

Change the method's return type from void to List<Cidade> , then replace the for loop with return c; 将方法的返回类型从void更改为List<Cidade> ,然后将for循环替换for return c; . (You could also remove the c variable and just do return cc.buscaCidadePorEstado(uf) .) (您也可以删除c变量,只return cc.buscaCidadePorEstado(uf) 。)

You'll still need to return something even when an exception occurs. 即使发生异常,您仍然需要返回一些内容。 You could put return null; 您可以将return null; within each of your catch blocks, or return Collections.emptyList() if you don't want the calling method to have to check for null results. 在每个catch块中,如果您不希望调用方法必须检查null结果,则return Collections.emptyList() Alternatively, you could throw a different exception type instead — for example, throw new CityLookupException(e); 另外,您可以抛出其他异常类型,例如, throw new CityLookupException(e); . (You'd need to create that class, of course.) (当然,您需要创建该类。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM