JDBC封装的工具类

1. JDBC封装的工具类

public class JDBCUtil
{
  private static Properties p = new Properties();
  private static ThreadLocal<Connection> tl = new ThreadLocal();
  
  static {
    InputStream stream = JDBCUtil.class.getResourceAsStream("/jdbc.properties");
    try{
      p.load(stream);
    } catch (Exception e) {
         e.printStackTrace();
    } finally {
      try {
        stream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  public static Connection getConnection()
  {
    Connection connection = (Connection)tl.get();
    if (connection == null) {
      try {
        Class.forName(p.getProperty("driver"));
        
        connection = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password"));
        
        tl.set(connection);
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
    return connection;
  }
  
  public static void close(Connection conn, PreparedStatement pst, ResultSet rs) {
    if (conn != null) {
      try {
        conn.close();
        tl.remove();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    if (pst != null) {
      try {
        pst.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
  

}

 

 2.JDBC的配置文件

driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username=hr
password=root

 

posted @ 2019-10-29 21:04  纳兰容若♫  阅读(99)  评论(0编辑  收藏  举报