簡體   English   中英

MySQL與Java的數據庫連接

[英]mysql db connection with java

我正在為MySQL使用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

僅當多個用戶正在訪問同一文件(例如abc.java)時,才會發生上述問題。

你應該做:

1)在finally塊中關閉PreparedStatement和Connection,因此,如果代碼出現exception您的代碼將正確關閉資源,否則可能會發生內存泄漏。

2)如果在您的代碼中使用類似ResultSet

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

然后,您應該先關閉它,然后再重新使用它...

3)您在abc.java的方法是靜態的嗎?

我將執行以下操作,在finally塊中移動close方法,以防止在發生異常情況下發生內存泄漏

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方法以釋放該設置...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM