0

I am in the process of designing a simple Java application which deals with insert/delete/update of records in a MySQL database using JDBC. I have a class Member which deals with the member's details.

class Member {
  ... // Private Members
  ... // Accessors
}

..and I have a handler to deal with the member records

class MemberHandler {
  public MemberHandler(){...}
  public void addMember(Member mem){...}
  public void removeMember(Member mem){...}
  public Member[] getMembers(){...}
}

All I am worried about is the method in which I establish connection to the database and disconnect. I can do it in two ways -

Method 1: I can have a member in MemberHandler Connection conn, establish connection while instantiating the class and close the connection when the object is no more needed. Here I would have a connection per object and I need not establish a connection whenever I need to do any database related activity. In this case, the disadvantage seems to be - when there is a loss in network connection, conn could become invalid.

class MemberHandler {
  private java.sql.Connection conn;
  ... // Other members
  private void createConnection(){/*creates the connection*/}
  private void closeConnection(){conn.close(); /*called when conn is no more needed*/}
}

Method 2: I can establish a connection when needed and close it when I am done with the activity. Disadvantage: everytime, I need to establish a connection and close it. For eg.,

...
...
private void addMember() {
  //establish connection
  //update database
  //close connection
}
...
...

Which of these two ways seems to be better? Or is there a third better way?

Thanks!

1 Answer 1

1

I would suggest you to go for connection-pooling

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.