oldhomemovie
oldhomemovie

Reputation: 15129

Establishing persistent connection to a database in Java

I've ran through several examples over the web, and found that every single time I need something from the DB, I should write the following code:

try
{
  // Step 1: Load the JDBC driver. 
  Class.forName("mysql_driver_name"); 
  // Step 2: Establish the connection to the database. 
  String url = "jdbc:string_to_mysql_server"; 
  Connection conn = DriverManager.getConnection(url,"user1","password");

  // fetch from the DB ...

}
catch (Exception e)
{
  System.err.println("Got an exception! "); 
  System.err.println(e.getMessage()); 
}

It's very annoying to put up this code every time I want something from the DB, so the question is - is there a way to only once connect entirely all my app to the DB somehow at the very start point, avoiding copy-pasting mentioned code, and then be able to do everything I want with DB?

I've quickly looked through NetBeans's Project menu, but didn't find any clue on how to configurate a persistent connection to a selected DB.

If it's important, i'm writing a purely desktop app, i.e. using Java SE. Also, it's worth mentioning that I'm a kinda beginner in Java.

Upvotes: 1

Views: 3145

Answers (3)

gmhk
gmhk

Reputation: 15940

You can follow this Method of Establishing the Conenction

  1. Create a Singleton class, which helps you to create a connection
  2. In your DAO or any helper Class, Call this Single instance, which has a connection
  3. Once you get the Conenction, write the operations that you want to perform on the database.
  4. Close the connection, that will do to fullfill your connection.

This will avoid the code, what you have written in your query. and this style will increases the readability and reduce the maintainability.

If you want any sample code let me know, I can provide you that

Upvotes: 1

mmmmmm
mmmmmm

Reputation: 32661

The connection pool idea is probably the best overal solution. However there is a simpler one in ypur case.

In your code conn goes out of scope in the method itwas created. There is no need to do that. You can create a method that includes all your code up to an including the line that assigns to conn. Then pass that conn variable to other parts of the program and use that for db work.

Upvotes: 1

crowne
crowne

Reputation: 8534

There are many connection pool options to choose from, I would suggest that you try Apache Common Db Connection Pool http://commons.apache.org/dbcp/.

Upvotes: 5

Related Questions