简体   繁体   中英

Does rs.getString() returns string type ? What is wrong with this code?

I am using oracle database. I am trying to access a table which has only one column containing some names in it. Though I have assigned the result returned from dept_name_list.getString("DEPT_NAME") in a string type variable and returned it, the error says "The method must return a result of String type".

String get_dept_list()
{
    trivialFunctions.establishConnection();
    try
    {
        stmt = conn.createStatement();
        sql = "select * from DEPARTMENT_LIST;";
        ResultSet dept_name_list = stmt.executeQuery(sql);
        if(dept_name_list.next())
        {
            String name = dept_name_list.getString("DEPT_NAME");
            return name;
        }
    }
    catch (SQLException e)
    {
        System.out.println("Problem in finding the dept_name_list");
    }
}

What is wrong in the code? I need to access the String names, does this part return a String name dept_name_list.getString("DEPT_NAME"); ?

The original code:

String get_dept_list()
{
    trivialFunctions.establishConnection();
    try
    {
        stmt = conn.createStatement();
        sql = "select * from DEPARTMENT_LIST;";
        ResultSet dept_name_list = stmt.executeQuery(sql);
        if(dept_name_list.next())
        {
            String name = dept_name_list.getString("DEPT_NAME");
            return name;
        }
    }
    catch (SQLException e)
    {
        System.out.println("Problem in finding the dept_name_list");
    }
}

The method is declared as returning a String . However, the only return statement is inside the if . You must make sure that all branches return a value. One way of doing this is to return null at the end of the method:

String get_dept_list()
{
    trivialFunctions.establishConnection();
    try
    {
        stmt = conn.createStatement();
        sql = "select * from DEPARTMENT_LIST;";
        ResultSet dept_name_list = stmt.executeQuery(sql);
        if(dept_name_list.next())
        {
            String name = dept_name_list.getString("DEPT_NAME");
            return name;
        }
    }
    catch (SQLException e)
    {
        System.out.println("Problem in finding the dept_name_list");
    }

    // In case the table is empty, return null:
    return null;
}

BTW - your code is leaking statements - you must close stmt and dept_name_list .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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