码迷,mamicode.com
首页 > 数据库 > 详细

JDBC封装的工具类

时间:2019-10-29 22:00:28      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:工具类   class   vat   source   cep   use   password   input   property   

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

 

JDBC封装的工具类

标签:工具类   class   vat   source   cep   use   password   input   property   

原文地址:https://www.cnblogs.com/zhulina-917/p/11761557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!