简体   繁体   English

MySQL与Java的数据库连接

[英]mysql db connection with java

I'm using type 4 driver for mysql. 我正在为MySQL使用4型驱动程序。 Code is given below. 代码如下。 In every java file i'm creating db connection and closing at the end. 在每个Java文件中,我都会创建数据库连接并最后关闭。 For example 例如

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

Like that in every java file I'm following the same way.. 像在每个Java文件中一样,我也遵循相同的方式。

In Dbconnection.java file 在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();
         }
      }
  }
}

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). 仅当多个用户正在访问同一文件(例如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. 1)在finally块中关闭PreparedStatement和Connection,因此,如果代码出现exception您的代码将正确关闭资源,否则可能会发生内存泄漏。

2) if in your code you use a ResultSet like 2)如果在您的代码中使用类似ResultSet

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

Then you should close it before reusing it again... 然后,您应该先关闭它,然后再重新使用它...

3) Is your method in abc.java static? 3)您在abc.java的方法是静态的吗?

I will do something like this, move the close method in the finally block, to prevent memory leak in case of exception 我将执行以下操作,在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
  }

You obviously need to add the new releaseResultSet method in Dbconnection to release the set... 您显然需要在Dbconnection中添加新的releaseResultSet方法以释放该设置...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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