开发者

Database Connection Management

I am in the process of designing a simple Ja开发者_如何学Pythonva 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!


I would suggest you to go for connection-pooling

  • c3po
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜