将 ResultSet 对象从方法传递到 Servlet 是否可取?

Is it advisable to pass a ResultSet object from a method to a Servlet?

假设我有一个 return 类型为 ResultSet 的方法。我可以将此对象传递给 Servlet 吗?我正面临那个对象是空的。

package sqlPackage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class SqlExample {
    public  ResultSet playerCountry() throws SQLException {
        
        ResultSet rs2 = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            String url2="jdbc:mysql://localhost:3306/mxplayerdb";
            
            String userName="root";
            String password="root";
            
            Connection connection2=DriverManager.getConnection(url2,userName,password);
            
            String query2="Select * from myplayers";
            
            Statement statement2=connection2.createStatement();
            ResultSet rs2Clone=statement2.executeQuery(query2);
      
            while(rs2Clone.next()) {
                String name=rs2Clone.getString("userName");
                System.out.println(name);//**this displays the relevant values**
            }
            rs2=rs2Clone;//**I had to do this as I was not able to return rs2CLone inside the try block**
            //return rs2Clone;
            
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        
        return rs2;// ***At this stage will this variable be null or referring to an object having data***
    }   
}

当我在 Servlet 中实例化此 class 并调用该方法时,它收到一个 空结果集对象 。 我究竟做错了什么?我们也不能 return 仅来自 try 块吗?

您最好不要 return 方法中的 ResultSet

这很容易导致资源泄漏,因为您被迫保持语句和连接打开。

更好的方法是使用 try-with-resourcestry-with-resources 的目的是确保资源可靠地关闭。

改变你的方法如下:

public List<String> readPlayerNameList() {
    List<String> nameList = new ArrayList<>();
    String userName = "root";
    String password = "root";
    String url = "jdbc:mysql://localhost:3306/mxplayerdb";
    try (Connection connection = DriverManager.getConnection(url, userName, password);
        Statement statement = connection.createStatement();) {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String query = "Select * from myplayers";
        try (ResultSet rs = statement.executeQuery(query)) {
            while (rs.next()) {
                String name = rs.getString("userName");
                System.out.println(name);
                nameList.add(name);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return nameList;
}