与java的mysql数据库连接

时间:2015-04-16 15:25:11

标签: java mysql

我正在使用mysql的type 4驱动程序。代码如下。在每个java文件中,我都在创建数据库连接并在结束时关闭。例如

在abc.java中

 Dbconnection db=null;
 Connection con=null;
 PreparedStatement pstmt = null; 
public ActionForward execute(----)
  {
 try{
    db=new Dbconnection();//instantiating user defined Dbconnection class object
    con=db.getConnection();//creating connection object
    ...........
    Login_Check formBean=(Login_Check)form;//bean class object

    pstmt=con.prepareStatement("select type from user_registration where user_name=? and password=? and user_status=?");
    //form parameter values
    pstmt.setString(1,formBean.getUname().trim());
    pstmt.setString(2,formBean.getPassword().trim());
    pstmt.setString(3,"Active");//user status should be active

    ResultSet rs=pstmt.executeQuery();

        if(rs.next())
        {
            ................
            db.releasePreparedStatement(pstmt);
            db.releaseConnection(con);

            return mapping.findForward(SUCCESS);//redirecting to success page
        }
        else
        {
            ActionErrors errors = new ActionErrors();
            errors.add("both", new ActionMessage("errors.both.wrong"));//if both user name and password is incorrect, gives an error message
            saveErrors(request,errors);

            //closing connection and prepareStatement objects
            db.releasePreparedStatement(pstmt);
            db.releaseConnection(con);

            return mapping.findForward(FAILURE);//redirecting to failure page
        }

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return mapping.findForward(FAILURE);//redirecting to failure page
  }

就像每个java文件中的那样,我都遵循相同的方式..

在Dbconnection.java文件中

public class Dbconnection
{
    Connection con=null;
    String DB_URL = "jdbc:mysql://localhost:3306/dbname";
    String USER = "abc";//db user name
    String PASS = "abc";//db password
    PreparedStatement pstmt = null;

     public synchronized Connection getConnection()
     {
       try
       {
          Class.forName("com.mysql.jdbc.Driver");//loading mysql driver 
          con = DriverManager.getConnection(DB_URL,USER,PASS);//connecting to mysql
       }
       catch(Exception e)
       {
          e.printStackTrace();
       }
         return con;
      }

      public void releaseConnection(Connection conn)//releasing Connection
      {
         if(conn!=null)
          {
             try
              {
                 conn.close();
              }
              catch(Exception e)
              {
                 e.printStackTrace();
              }
        }
    }

    public void releasePreparedStatement(PreparedStatement stmt)//closing PreparedStatement object
    {
       if(stmt!=null)
       {
         try
         {
              stmt.close();
         }
         catch(Exception e)
         {
             e.printStackTrace();
         }
      }
  }
}

但问题是我有时会收到成功的消息。但有时我会收到失败的消息。在服务器中我收到错误

The operation is not allowed after ResultSet is closed

只有当多个用户访问同一个文件时(ex abc.java),才会出现上述问题。

1 个答案:

答案 0 :(得分:0)

你应该这样做:

1)在finally块中关闭PreparedStatement和Connection,因此如果代码获得exception,您的代码将正确关闭资源,否则您可能会发生内存泄漏。

2)如果在您的代码中使用了ResultSet之类的

ResultSet rs = pstm.executeQuery();
......

然后你应该在重新使用它之前关闭它......

3)您的方法是否在abc.java静态?

我会做这样的事情,在close块中移动finally方法,以防止在异常情况下发生内存泄漏

public ActionForward execute(----) {
    Dbconnection db=null;
    Connection con=null;
    PreparedStatement pstmt = null; 
    ResultSet rs = null;

    try {
        db=new Dbconnection();//instantiating user defined Dbconnection class object
        con=db.getConnection();//creating connection object

        // some code
        Login_Check formBean = (Login_Check) form;//bean class object

        pstmt = con.prepareStatement("select type from user_registration where user_name=? and password=? and user_status=?");
        //form parameter values
        pstmt.setString(1, formBean.getUname().trim());
        pstmt.setString(2, formBean.getPassword().trim());
        pstmt.setString(3, "Active"); //user status should be active

        rs = pstmt.executeQuery();

        if(rs.next())
        {
            /* some code */
            return mapping.findForward(SUCCESS);//redirecting to success page
        }
        else
        {
            ActionErrors errors = new ActionErrors();
            errors.add("both", new ActionMessage("errors.both.wrong"));//if both user name and password is incorrect, gives an error message
            saveErrors(request,errors);
            return mapping.findForward(FAILURE);//redirecting to failure page
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally {
        db.releaseResultSet(rs);
        db.releasePreparedStatement(pstmt);
        db.releaseConnection(con);
    }

    return mapping.findForward(FAILURE);//redirecting to failure page
  }

你显然需要在Dbconnection中添加新的releaseResultSet方法来释放集...