Java中的方法返回null

时间:2018-03-02 16:01:40

标签: java

我创建了一个类(OracleConnector2Test),它接收作为参数2的值,在基础中进行查询并在Eclipse控制台中返回该查询的结果。 在类(OracleConnector2TestBuscaEstrategias)中,我实例化了类(OracleConnector2Test),我传递参数(“179”,“319”)并让Eclipse在控制台屏幕上显示结果。 返回的值是正确的,但在Eclipse控制台中显示消息:

查询结果:null。

如果数据库中的查询返回2个值(Facilities 179和Consumer.GOV Clear TV 319),我无法理解为什么消息(Query Result:null)。

按照下面的Java和Print Eclipse的Print Screen中的代码进行操作。

类OracleConnector2Test

ArrayList<Double> RPM = new ArrayList<>();
ArrayList<Double> bCoeffs = new ArrayList<>();
ArrayList<Double> filteredRPM = new ArrayList<>();

类OracleConnector2TestBuscaEstrategias

public class OracleConnector2Test {

String resultado;

public String returnDb(String Id_Estrategia1, String Id_Estrategia2) {
    // Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
    String dbUrl = "jdbc:oracle:thin:@10.5.12.116:1521:desenv01";

    // Database Username
    String username = "bkofficeadm";

    // Database Password
    String password = "bkofficeadmdesenv01";

    // Query to Execute
    String query = "SELECT  DS_ESTRATEGIA, ID_ESTRATEGIA" + " FROM TB_BKOFFICE_ESTRATEGIA"
            + " WHERE ID_ESTRATEGIA  IN (" + Id_Estrategia1 + ", " + Id_Estrategia2 + ")";

    try {
        // Load mysql jdbc driver
        Class.forName("oracle.jdbc.driver.OracleDriver");

        // Create Connection to DB
        Connection con = DriverManager.getConnection(dbUrl, username, password);

        // Create Statement Object
        Statement stmt = con.createStatement();

        // Execute the SQL Query. Store results in ResultSet
        ResultSet rs = stmt.executeQuery(query);

        // While Loop to iterate through all data and print results
        while (rs.next()) {
            String DS_ESTRATEGIA = rs.getString(1);
            String ID_ESTRATEGIA = rs.getString(2);
            System.out.println(DS_ESTRATEGIA + "  " + ID_ESTRATEGIA);
        }
        // closing DB Connection
        con.close();
    } catch (ClassNotFoundException e) {

        e.printStackTrace();

    } catch (SQLException e) {

        e.printStackTrace();

    }
    return resultado;
  }
}

it is forbidden by Google's style guide

1 个答案:

答案 0 :(得分:0)

您完成了String resultado;,然后return resultado;从未为其分配任何内容。

将结果分配给resultdao

类似的东西:

StringBuilder sb = new StringBuilder();
while (rs.next()) {
  String DS_ESTRATEGIA = rs.getString(1);
  String ID_ESTRATEGIA = rs.getString(2);
  System.out.println(DS_ESTRATEGIA + "  " + ID_ESTRATEGIA);
  sb.append(DS_ESTRATEGIA + "  " + ID_ESTRATEGIA + "\n");
}
resultdao = sb.toString();

实际上,您最好还是退回List<String>

List<String> resultdao = new ArrayList<>();

public List<String> returnDb(String Id_Estrategia1, String Id_Estrategia2) {
  ...
  while (rs.next()) {
    String DS_ESTRATEGIA = rs.getString(1);
    String ID_ESTRATEGIA = rs.getString(2);
    System.out.println(DS_ESTRATEGIA + "  " + ID_ESTRATEGIA);
    resultdao.add(DS_ESTRATEGIA + "  " + ID_ESTRATEGIA);
  }
  ...