【问题标题】:problem with closing connection on db with servlet使用servlet关闭数据库连接的问题
【发布时间】:2011-09-26 09:54:12
【问题描述】:

我第一次调试/运行应用程序时,我正在尝试使用 tomcat 运行我的应用程序,它的工作正常。但是当我第二次尝试运行时,我收到错误“XJ040”。

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

我认为问题是因为关闭连接有问题。因为当我停止服务器时,问题会消失,直到第二次运行。

这里是代码:

      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) {

    }

感谢您的帮助

【问题讨论】:

  • 为什么不在 close 函数的开头放置一个 print 语句,看看它是否会运行。

标签: java sql derby


【解决方案1】:

最好总是在 finally 中关闭连接

connect = DriverManager.getConnection(...)

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

在您的代码中,如果您在 parseInt(version) 或 exequteQuery() 中遇到异常,则连接不会关闭

在你的情况下,我认为没有必要关闭结果集,因为无论如何你都在关闭连接。

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

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

}

是有问题的,因为 1. 如果 resultSet.close() 抛出异常,则连接永远不会关闭,并且 2. 在此方法中您不会看到任何异常。我建议至少记录捕获的异常。

【讨论】:

  • 一个补充:如果您在方法中使用后关闭语句和连接,我建议不要将它们作为类成员在方法之间共享,而是使用局部变量。这将减少尝试重复使用不存在的东西的危险。
猜你喜欢
  • 2012-02-29
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
相关资源
最近更新 更多