gpt4 book ai didi

java - “结果集关闭后操作不可用”

转载 作者:行者123 更新时间:2023-11-29 20:51:56 26 4
gpt4 key购买 nike

我在这里查看了发生这种情况的原因,我唯一能看到的原因是开放连接。在我的代码中,我关闭一个连接并注册一个新连接以重新打开。

try{

//Registration of driver, connector
String myDriver = "com.mysql.jdbc.Driver";
String myURL = "jdbc:mysql://localhost:3306/maintenance";
Class.forName(myDriver);
Connection connection = DriverManager.getConnection(myURL, "admin", "");


//Call MySQL for table names of users
String query = "SELECT users FROM goods";

Statement st = connection.createStatement();


ResultSet res = st.executeQuery(query);

while (res.next()) {

String name = res.getString("users");


if(name.equals(username)){
connection.close();
res.close();
try{
Connection connection2;
connection2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/maintenance", "admin", "");
query = "SELECT idkeys FROM goods";
Statement st2;
st2 = connection2.createStatement();
ResultSet res2;
res2 = st2.executeQuery(query);
String myDriver2 = "com.mysql.jdbc.Driver";
Class.forName(myDriver2);
connection2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/maintenance", "admin", "");
while (res2.next()) {

keyed = res2.getObject("idkeys");

if (keyed.equals(sanitizedPass)){
checked = true;
connection2.close();
res2.close();

}
}
} catch (Exception e2){
System.err.println(e2.getMessage());

}

}

}
//Close connections
if (!checked){
res.close();
connection.close();
}
}
catch(Exception e)
{
System.err.println(e.getMessage());
}

return checked;

在我的代码中,至少据我所知,没有发生这样的事情。为什么还是会被抛出?

最佳答案

try {
String myURL = "jdbc:mysql://localhost:3306/maintenance";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(myURL, "admin", "");

String query = "SELECT users, idkeys FROM goods";
Statement st = connection.createStatement();
ResultSet res = st.executeQuery(query);

while (res.next()) {
String name = res.getString("users");
if (name.equals(username)) {
Object keyed = res.getObject("idkeys");
if (keyed.equals(sanitizedPass)) {
checked = true;
break;
}
}
}
return checked;
} catch (Exception e) {
e.printStackTrace(); // or do some reasonable error logging
} finally {
// close the ResultSet, Statement and Connection here
}
  1. 您不需要创建多个连接;一个就够了。
  2. 即使您正在查询同一个表,您也会向数据库发送两个不同的查询;相反,在同一查询中返回两个字段(请参阅上面的查询)

关于java - “结果集关闭后操作不可用”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37970547/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com