#singleton

How to create a java singleton to connect to mysql databases


It's just that simple! We need to create a SqlConnection Class.

code:

package yourpackage;

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

public class SqlConnection {

	private static String url = "jdbc:mysql://localhost:3306/"
	private static String dbName = "databaseName"
	private static String driver = "com.mysql.jdbc.Driver"
	private static String userName = "root"
	private static String password = "password"
	
	private static Connection conn = null;
	
	private static SqlConnection INSTANCE = null;
		
	private SqlConnection(){
		try {
			Class.forName(driver).newInstance();
			SqlConnection.conn = DriverManager.getConnection(url+dbName,userName,password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//the instance is created just one time
	public static SqlConnection getInstance() {
		if(INSTANCE == null) {
			INSTANCE = new SqlConnection();
		}
		return INSTANCE;
	}
	
	public Connection getConnection(){
		return conn;
	}
}

HOW TO USE:



code:
Connection localConn = SqlConnection.getInstance().getConnection();
Statement st;
st = localConn.createStatement();
localConn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
ResultSet res = st.executeQuery("SELECT * FROM user"
			    + "  WHERE userId > 10 ");
					
st.close();

Close only st , do not close localConn

view more about patters

________
ZXCoders

Subscribe to RSS - #singleton