JDBC工具類(獲取鏈接&釋放資源)

學習JDBC時抽取的一個獲取鏈接conn和釋放資源的工具類,供之後回顧之用。工具

Properties類繼承自Hashtable類而且實現了Map接口,也是使用一種鍵值對的形式來保存屬性集。鍵和值都是字符串類型。學習

/**
 * JDBC的工具類
 * 做用:獲取鏈接、釋放資源
 *
 */
public class JDBCUtil {
	private JDBCUtil(){}
	private static JDBCUtil instance = null;
	private static Properties p = null;
	
	//靜態代碼塊,調用靜態方法時運行獲取Properties對象
	static{
		try {
			instance = new JDBCUtil();
			//獲得當前ClassPath的絕對URI路徑。經過當前線程獲取類加載器,讀取指定資源的輸入流
			InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
			 p = new Properties();
			p.load(is);//加載流資源
			Class.forName(p.getProperty("driverClassName"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static JDBCUtil newInstance(){
		return instance;
	}
	//獲取鏈接對象
	public Connection getConn(){
		try {
			return DriverManager.getConnection(p.getProperty("url"),p.getProperty("username"), p.getProperty("password"));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	//釋放資源(資源、(預)加載對象、鏈接對象)
	public void release(Statement st,ResultSet rs,Connection conn){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(st!=null){
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
相關文章
相關標籤/搜索