package com.baizhi.JDBCUtil; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; public class JDBCUtil { static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); private static String className; private static String url; private static String user; private static String pwd; static Properties pro = null; static { //创建properties pro = new Properties(); //获取输入流 InputStream is = JDBCUtil.class.getResourceAsStream("/JDBCUtil.properties"); //读取JDBCUtil.properties try { pro.load(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //获取键值对 className = pro.getProperty("ClassName"); url = pro.getProperty("url"); user = pro.getProperty("user"); pwd = pro.getProperty("psw"); } //加载驱动.获取连接 public static Connection getConn() { if (tl.get() == null) { try { Class.forName(className); Connection conn = DriverManager.getConnection(url, user,pwd); tl.set(conn); } catch (Exception e) { throw new RuntimeException(e); } } return tl.get(); } //关闭资源 public static void closeAll(Connection conn,PreparedStatement pstm,ResultSet rs) { if(rs != null) { try { rs.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if(pstm != null) { try { pstm.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if(conn != null) { try { tl.remove(); conn.close(); } catch (SQLException e) { throw new RuntimeException(e+"关闭conn链接出错"); } } } }
配置文件 (properties)
ClassName = oracle.jdbc.OracleDriver url = jdbc:oracle:thin:@localhost:1521:xe user = hr psw = hr