jdbc

package com.xx.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 JdbcUtilk {
	private static Properties map = new Properties();

	static{
		InputStream is = null;
		try {
			// 讀取配置文件,獲取信息
			//is = new FileInputStream("d:/workspace/Jdbc/src/conf/conn.properties");
			is = JdbcUtilk.class.getResourceAsStream("/conf/conn.properties");
			map.load(is);

		} catch (Exception e) {
			throw new RuntimeException("配置文件讀取出現錯誤");
		} finally{
			if(is!=null) try{ is.close(); }catch(Exception e){}
		}
	}
	
	private static final ThreadLocal<Connection> tol = new ThreadLocal<Connection>();
	
	public static Connection getConnection(){
		try {
			Connection conn = tol.get();
			if(conn == null){
				Class.forName( map.getProperty("driver") );
			    conn = DriverManager.getConnection( map.getProperty("url"),map.getProperty("username"),map.getProperty("password"));
			    tol.set(conn);
			}
			return conn;
		} catch (Exception e) {
			throw new RuntimeException("出現問題,連接無法獲取");
		}
	}

	public static void close(ResultSet rs,Statement stm,Connection conn){
		if(rs!=null) try{ rs.close(); }catch(Exception e){}
		if(stm!=null) try{ stm.close(); }catch(Exception e){}
		if(conn!=null) try{ conn.close(); tol.remove(); }catch(Exception e){}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章