假设我有一个返回类型为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中实例化该类并调用此方法时,它接收到一个null ResultSet对象.我做错了什么?我们也可以不返回从一个尝试块吗?
最好不要从方法中返回ResultSet
。
这很容易导致资源泄漏,因为你被迫保持语句和连接打开。
一个更好的方法是使用try-with-resources
。try-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;
}