Java - NULL ResultSet

时间:2016-11-16 17:01:03

标签: java mysql resultset

我有一个从MySQL表中获取数据的函数

public ResultSet getAddressID(String city) throws SQLException{
        String q = "SELECT PK_ADDRESS_ID FROM tbl_addresses WHERE city =" + "\""+ city+ "\";";
        ResultSet rs = executeSearch(q);
        return rs;
    }

当我尝试System.out.println(n.getAddressID("Sheffield"));时,它会返回null。即使我的表中有数据,为什么会发生这种情况(见图)。

enter image description here

public ResultSet executeSearch(String q){
    openConnection();
    try{
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(q);
        closeConnection();
        return resultSet;
    }
    catch (Exception e){
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
    finally {
        closeConnection();
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

问题似乎出在你的executeSearch方法中; finally块总是会执行,所以通过在finally块中返回null,你基本上覆盖你在try块中返回的内容!

这可能是一种替代解决方案;请注意,我在方法结束时返回,而不是在try-catch-finally块的任何部分内返回。

/**
 * Converts a provided ResultSet into a generic List so that the
 * ResultSet can be closed while the data persists.
 * Source: http://stackoverflow.com/a/7507225/899126
 */
public List convertResultSetToList(ResultSet rs) throws SQLException
{
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    List list = new ArrayList(50);

    while (rs.next())
    {
        HashMap row = new HashMap(columns);
        for(int i = 1; i <= columns; ++i)
        {
            row.put(md.getColumnName(i), rs.getObject(i));
        }
        list.add(row);
    }

    return list;
}

public List executeSearch(String q)
{
    List toReturn;
    openConnection();
    try {
        Statement statement = connection.createStatement();
        toReturn = this.convertResultSetToList(statement.executeQuery(q));
    }
    catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
        toReturn = new ArrayList();
    }
    finally {
        closeConnection();
    }

    return toReturn;
}