【问题标题】:Which Place to write connection.close() and preparedstatement.close()哪个地方写connection.close()和preparedstatement.close()
【发布时间】:2014-10-14 08:29:55
【问题描述】:

我是 JDBC 新手...

Student 类有 Constructor、add()、update() 和 delete() 等方法...

在构造函数中打开一个连接。 conn.close() 和 pstmt.close() 在下面的代码中写哪个地方帮助我

class Student
{
    Connection conn;

    PreparedStatement  pstmt;

    ResultSet rs;

    public Student()
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");

            conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
        }
        catch(Exception e)
        {
             System.out.println("Error :"+e.getMessage());
        }

    }


    public void add(int rollno,String name)
    {
        try
        {
            pstmt = conn.prepareStatement("insert into student values (?, ?)");

            pstmt.setInt(1,rollno);

            pstmt.setString(2, name);

            int i = pstmt.executeUpdate();

            if (i != 0) {
                System.out.println("Record Inserted");
            } else {
                System.out.println("Record Not Inserted");
            }

        }
        catch(Exception e)
        {
             System.out.println("Error :"+e.getMessage());
        }

    }

    public void update(int rollno,String name)
    {
        try
        {
            pstmt = conn.prepareStatement("update student set name=? where rollno=?");

            pstmt.setString(1, name);

            pstmt.setInt(2,rollno);


            int i = pstmt.executeUpdate();

            if (i != 0) {
                System.out.println("Record Updated");
            } else {
                System.out.println("Record Not Updated");
            }


        }
        catch(Exception e)
        {
             System.out.println("Error :"+e.getMessage());
        }
    }

    public void delete(int rollno)
    {
        try
        {
            pstmt = conn.prepareStatement("delete from student where rollno=?");

            pstmt.setInt(1,rollno);


            int i = pstmt.executeUpdate();

            if (i != 0) {
                System.out.println("Record Deleted");
            } else {
                System.out.println("Record Not Deleted");
            }

        }
        catch(Exception e)
        {
             System.out.println("Error :"+e.getMessage());
        }
    }

}

【问题讨论】:

    标签: java jdbc database-connection prepared-statement


    【解决方案1】:

    我猜你应该添加另一个方法来关闭连接,并在你完成操作后在你的对象上调用它。

    public void closeConnection() {
        conn.close();
    }
    

    另外,最好创建另一种方法来打开连接,而不是从构造函数中打开它。

    【讨论】:

      【解决方案2】:

      根据您发布的示例代码,您尝试执行的所有操作(如 Add UpdateDelete 似乎都使用全局创建并在构造函数“Student( )”。 This is not a standard practice

      根据标准,您不应该这样做,您应该在“添加”、“更新”和“删除”等每个操作上分别创建新连接作为 local 变量

      另外请记住,如果您使用的是“Bean 托管事务”,那么您需要在关闭它之前提交该事务。或者在 finally 块中添加 conn.commit();

      这是一个关于你的方法应该如何的简单示例

      public void add(int rollno,String name)
      {
          Connection conn = null;
          PreparedStatement pstmt = null;
          try
          {
              pstmt = conn.prepareStatement("insert into student values (?, ?)");
      
              pstmt.setInt(1,rollno);
      
              pstmt.setString(2, name);
      
              int i = pstmt.executeUpdate();
      
              if (i != 0) {
                  System.out.println("Record Inserted");
              } else {
                  System.out.println("Record Not Inserted");
              }
      
          } catch(Exception e) {
               System.out.println("Error :"+e.getMessage());
          } finally {
               if(pstmt!=null) {
                   pstmt.close();
               }
               if(conn!=null) {
                   conn.comit(); // Add this line ONLY if you use bean managed transaction
                   conn.close();
               }
          }
      
      }
      

      【讨论】:

      • 好极了...感谢您的回答。 . .
      • 如果您认为我的答案值得,您可以标记为正确答案
      【解决方案3】:

      首先,我不会在构造函数中打开连接,因为它会导致许多连接长时间打开而不被使用,并且由于连接是有限的资源,你应该保持它们打开为尽可能少的时间。

      我会在每个使用它的方法(addupdatedelete 等)中打开和关闭连接(以及准备好的语句)。这样连接只会在需要时打开。

      【讨论】:

        【解决方案4】:

        您可以使用 try-catch-finally 块并在 finally 中关闭连接。

        Connection con;
        try
        {
          con = new Connection(...);
        }
        catch (Exception e)
        {
         //Error Handling
        }
        finally
        {
          connection.close();
        }
        

        或者您使用 try-with-resource 并让 VM 负责关闭连接(在这种情况下,您不需要将 Connection 声明为字段,但每个操作都有一个):

        try(Connection con = new Connection(...))
        {
        
        }
        catch()
        {
        
        }
        

        【讨论】:

        • 供参考 - 第二个 try-with-resource 是在 Java 7 中引入的
        【解决方案5】:

        catch 块之后添加finally 块以关闭PreparedStatementConnection 对象。类似的东西

        catch (Exception d) {
           //do whatever you want when exception occurs
        }
        finally {
            //close resultset
            //close prepared statement
            //close connection object
        }
        

        finally 确保在控件返回之前关闭资源。即使您在 try 块内使用 return,资源也会被关闭。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-13
          • 2011-12-04
          • 1970-01-01
          • 2021-05-15
          • 1970-01-01
          • 2013-06-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多