【发布时间】:2014-07-20 14:28:13
【问题描述】:
我在下面有一个基本代码 sn-p 但它不起作用。它可能是什么问题。
public List<String> getStores() throws SQLException{
List<String> store_id=new ArrayList<>();
String query="select distinct(store_id) from stores";
Connection con=ConnectDatabase.getDb2ConObj();
Statement stmt=con.createStatement();
java.sql.ResultSet rsResultSet=stmt.executeQuery(query);
while(rsResultSet.next()){
store_id.add(rsResultSet.getString(1));
}
con.close();
return store_id;
}
抛出以下异常
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:888)
at com.mysql.jdbc.Connection.checkClosed(Connection.java:1931)
at com.mysql.jdbc.Connection.createStatement(Connection.java:3087)
at com.mysql.jdbc.Connection.createStatement(Connection.java:3069)
at com.dao.StoreDao.getStores(StoreDao.java:52)
at org.apache.jsp.adminViewAllStore_jsp._jspService(adminViewAllStore_jsp.java:119)
ConnectDatabse 的代码是
public class ConnectDatabase {
static Connection con=null;
static String connectionString="jdbc:mysql://localhost:3306/ayurveda";
static String username="root";
static String password="";
public static Connection getDb2ConObj(){
if(con==null){
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(connectionString,username,password);
}
catch(ClassNotFoundException | SQLException e)
{
System.out.println("Connect initialized with error"+e.getMessage());
e.printStackTrace();
}
}
return con;
}
我无法理解相同的原因。可能是什么问题。因为我在完成连接后关闭了连接。
【问题讨论】:
-
你得到了对象,却没有打开连接?
-
ConnectDatabase是什么? -
您可能正在将您的连接缓存在
ConnectDatabase.getDb2ConObj()中,然后在下次调用此方法时返回相同的连接?您最好使用连接池,而不是尝试维护自己的连接池。请发布ConnectDatabase的代码,我们可以确认。 -
嗨,已编辑问题
标签: java mysql database-connection