Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Singleton JDBC Connection - is this the best way?

800308Oct 17 2007 — edited Oct 17 2007
Hi,

I'm trying to share a single JDBC connection throughout my model (without passing it down from the controler and passing it around model).

The below class seems to work OK, but is it the best way?

I'm planning to use it in a Swing application. Whilst I realise that Swing applications are inherently multi-threaded, I guess everything I need to do can be done with the constraint that all access to model happens on the Event Dispatch Thread... and the user will just have to wear any unresponsiveness.
package datatable.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

abstract public class MySqlConnection {
	
	public static final String URL = "jdbc:mysql://localhost/test";
	public static final String USERNAME = "keith";//case sensitive
	private static final String PASSWORD = "********";//case sensitive
	
	private static final Connection theConnection;
	
	static {
		String driverClassName = "com.mysql.jdbc.Driver";
		try {
			Class.forName(driverClassName);
			theConnection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (Exception e) {
			throw new DAOException("Failed to register JDBC driver class \""+driverClassName+"\"", e);
		}
	}
	
	public static Connection get() {
		return(theConnection);
	}	
}
Is there a better solution short of c3po? Which I played with, but couldn't work out how to configure.

I would be grateful for any suggestions/opinions/comments.

PS: The production version would get the URL, USERNAME, and PASSWORD from a Properties file.

Cheers & Thanx, keith.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 14 2007
Added on Oct 17 2007
7 comments
3,252 views