Java JDBC技术抽象出来的公共类,个人觉得已经很完美了

package com.bdqn.jdbc.day1.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtil {

	private static Properties info = new Properties();

	static {
		try {
			InputStream is = JdbcUtil.class.getResourceAsStream("/com/bdqn/jdbc/day1/util/config.properties");
			info.load(is);
			is.close();
		} catch (Exception e) {// 静态代码块中如果try-catch 想抛出异常 只有一种
			throw new ExceptionInInitializerError(e);
		}
	}

	private static final ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	
	public static Connection getConnection() throws Exception {
		Connection conn = tl.get();
		if (conn == null) {
			Class.forName(info.getProperty("driver"));
			conn = DriverManager.getConnection(info.getProperty("url"),
					info.getProperty("username"), info.getProperty("password"));
			tl.set(conn);
		}
		return conn ;
	}
	public static void release(ResultSet rs, Statement stm ,  Connection conn ){
		if(rs!=null) try {rs.close();}catch(Exception ex){}
		if(stm!=null) try {stm.close();}catch(Exception ex){}
		if(conn!=null) try {conn.close();}catch(Exception ex){}
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(getConnection());
	}
}

发布了50 篇原创文章 · 获赞 33 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/leilei107/article/details/17025895