简体   繁体   中英

mysql db connection with java

I'm using type 4 driver for mysql. Code is given below. In every java file i'm creating db connection and closing at the end. For example

In 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
  }

Like that in every java file I'm following the same way..

In Dbconnection.java file

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();
         }
      }
  }
}

But the problem is sometimes I'm getting a success message. But some times I'm getting a failure message. In server i'm getting error

The operation is not allowed after ResultSet is closed

The above problem is occurs only while multiple users are accessing the same file (ex abc.java).

You should do:

1) Close the PreparedStatement and Connection in a finally block, so if the code get an exception your code will properly close the resources, otherwise you could have a memory leak.

2) if in your code you use a ResultSet like

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

Then you should close it before reusing it again...

3) Is your method in abc.java static?

I will do something like this, move the close method in the finally block, to prevent memory leak in case of exception

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
  }

You obviously need to add the new releaseResultSet method in Dbconnection to release the set...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM