File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes how to handle a database connection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "how to handle a database connection" Watch "how to handle a database connection" New topic

how to handle a database connection

Scott Hibbard

Joined: Jul 20, 2010
Posts: 9
I'm in need of some design advise regarding handling a database connection for a small GUI.

When/how often should you open and close the database file? It seems terribly inefficient to open and close the database every time you need to read or write to it. So far I'm trying to open it once and close it once on exit. Does that sound like the way to go? Are there any downsides to that approach?

Assuming that's the way to go, how do you go about doing this? Right now I have the following code in main:

Here's PersonListView

I'm using a very simple MVC pattern. PersonListView handles the swing components including a JFrame to hold it all together. I'd like the database to be available until the window is closed which it's not.

Can someone explain why db.close() is reached before the window is closed? I'm assuming some new threads are kicked off somewhere in there but I'm a little fuzzy on the details.

The big question I'm looking for is this: How do I gracefully handle resources like a database in a locally run swing app - specifically on close? Should I create a helper class to handle the connection? Where do I put code to handle the cleanup when the window is closed?

Thanks in advance for any and all help!
Scott Hibbard

Joined: Jul 20, 2010
Posts: 9
nevermind. I figured it out. :-)

I changed the default close operation to do nothing and added a Window Listener to listen for a windowClosing event. Using the listener, I was able to close the database, dispose of my frame and exit the program.

jQuery in Action, 2nd edition
subject: how to handle a database connection
Similar Threads
text box - GridBagLayout
JFrame problem
Transforming Code
Passing values to constructor