日期:2014-05-16  浏览次数:20395 次

JDBC备忘录3_常用的JDBC单例类

?

要点:

1、类设计

2、单例模式

3、resultSet,Statement,Connection的关闭顺序以及异常捕获

?

1、工具类,不让其他类继承,所以是final;url,password,driver,class等常量信息

2、单例模式,饿汉模式和懒汉模式的区别,双重加锁

(1)单例模式三要素:静态私有的成员变量,私有构造方法,防止外部实例化,公共的获取方法

(2)饿汉模式,饥所以及时加载;懒汉模式,懒所以延迟加载;

3、打开顺序:Connection --> Statement(PreparedStatement) --> Result

关闭顺序: Result --> Statement --> Connection

?

?

package com.zhaoyp.jdbc.util;

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

public final class JdbcUtils {
	
	private static final String URL = "jdbc:mysql://localhost:3306/jdbc";
	private static final String USERNAME = "root";
	private static final String PASSWORD = "123";
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	
	//延迟加载,需要new的时候才去new
	//懒汉模式,懒所以延迟加载
	//饿汉模式,饿所以及时加载
//	private static JdbcUtils instance = new JdbcUtils();
	private static JdbcUtils instance = null;
	
	private JdbcUtils() {
	}
	
//	public static synchronized JdbcUtils getInstance() {
//		if(instance == null) {
//			instance = new JdbcUtils();
//		}
//		return instance;
//	}
	
	
	//double-check
	public static JdbcUtils getInstance() {
		if(instance == null) {
			//class级别锁
			synchronized (JdbcUtils.class) {
				if(instance == null) {
					instance = new JdbcUtils();
				}
			}
		}
		return instance;
	}
	
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(URL, USERNAME, PASSWORD);
	}
	
	public static void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if(rs!=null && !rs.isClosed())
				rs.close();
		} catch (Exception e) {
			System.out.println("异常。。");
		} finally {
			try {
				if(st != null && !st.isClosed())
					st.close();
			} catch (Exception e) {
				System.out.println("st 异常");
			} finally {
				try {
					if(conn != null && !conn.isClosed()) 
						conn.close();
				} catch (Exception e) {
					System.out.println("conn 异常");
				} finally {
					System.out.println("程序结束");
				}
				
			}
		}
	}
}

?