简体   繁体   English

Java-NULL ResultSet

[英]Java - NULL ResultSet

I have a function to fetch data from MySQL table 我有一个从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;
    }

When I try System.out.println(n.getAddressID("Sheffield")); 当我尝试System.out.println(n.getAddressID("Sheffield")); it returns null . 它返回null Why this happened even though there are data in my table (see picture). 为什么即使我的表中有数据,也会发生这种情况(见图)。

在此处输入图片说明

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;
    }
}

The problem appears to be in your executeSearch method; 问题似乎出在您的executeSearch方法中。 the finally block will always execute, so by returning null in the finally block, you essentially override what you returned in the try block! finally块将始终执行,因此,通过在finally块中返回null,您实际上将覆盖 try块中返回的内容!

This could be an alternative solution; 这可能是替代解决方案; note that I'm returning at the end of the method instead of within any parts of the try-catch-finally block. 请注意,我将在方法末尾而不是在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;
}

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

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