2011-09-26 40 views
2

我想运行我的应用程序与tomcat第一次,我正在调试/运行应用程序其工作正常。但是当我第二次尝试运行时,出现错误“XJ040”。与关闭数据库与servlet连接的问题

 "Failed to start database 'C:\Documents and Settings\vitaly87\.netbeans-  derby\articals' with class loader WebappClassLoader 
     context: /WebApplication1 
    delegate: false 
     repositories: 

我认为问题是由于一些错误关闭connections.Because当我停止我的服务器,问题消失了,直到第二次运行。

这里的代码:如果你有一个例外

 private Connection connect = null; 
//private Statement stmt = null; 
private PreparedStatement preparedStatement = null; 
private ResultSet resultSet = null; 
    public ArrayList<story> stories=new ArrayList<story>(); 
      void getStories(String version) throws SQLException{ 

     try{ 

     Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); 

      }catch(ClassNotFoundException e){ 
       System.out.println(e); 
      } 
      connect = DriverManager.getConnection("jdbc:derby:C:\\Documents and Settings\\vitaly87\\.netbeans-derby\\articals", "admin", "admin"); 
     // statement = connect.createStatement(); 
       int ArticlesId= Integer.parseInt(version); 
      preparedStatement = connect.prepareStatement("SELECT * FROM admin.articles where id>"+ArticlesId+""); 
       resultSet = preparedStatement.executeQuery(); 
      while (resultSet.next()) { 
    stories.add(new  story(resultSet.getString("title"),resultSet.getString("date"),resultSet.getString("text"))); 
} 
      close(); 
      } 
      //close connection 
private void close() { 
    try { 
     if (resultSet != null) { 
      resultSet.close(); 
     } 



     if (connect != null) { 
      connect.close(); 
     } 
    } catch (Exception e) { 

    } 

感谢在最后

connect = DriverManager.getConnection(...) 

try 
{ 
    // use connection 
} 
finally 
{ 
    try 
    { 
     connect.close() 
    } 
    catch (SQLException e) 
    { 
     // log e 
    } 
} 

帮助

+0

为什么不在close函数的开始处放一个print语句来查看它是否被运行。 – BobTurbo

回答

1

最好的总是紧密联系在代码中的连接不会被关闭例如在parseInt(版本)或exequteQuery()中

也在yo我不认为关闭结果集是必要的,因为无论如何您都要关闭连接。

try { 
    if (resultSet != null) { 
     resultSet.close(); 
    } 

    if (connect != null) { 
     connect.close(); 
    } 
} catch (Exception e) { 

} 

是问题,因为1.如果resultSet.close()抛出一个异常的连接永远不会关闭和2.你不会看到在这个方法中抛出的异常。我建议至少记录捕捉到的异常。

+0

另外还有一点:如果你在你的方法中使用后关闭了语句和连接,看起来我建议不要将它们作为类成员在方法中共享,而是使用局部变量。这将减少尝试重用那些不存在的东西的危险。 – Gandalf