JDBC原始工具类(java)

/**

  • JDBC工具类 实例工具类
  • 单例模式 饿汉
  • @author 11561

*/
导包:
在这里插入图片描述

/**
  * 私有化构造方法
  */
 private JDBCUtil() {
  // TODO Auto-generated constructor stub
 }
 
 /**私有化单例常量*/
 private static final JDBCUtil INSTANCE = new JDBCUtil();
 
 /**
  * 公开静态方法获取单例工具类对象
  * @return
  */
 public static JDBCUtil getInstance() {
  return INSTANCE;
 }
 
 /**
  * 实例方法获取连接
  * @return
  * @throws SQLException 
  * @throws IOException 
  */
 public Connection getConnection() throws SQLException, IOException {
  
  //获取配置文件
  Properties properties = new Properties();
  
  //通过当前线程对象获取类加载器再获取文件输入流和缓冲流
  Thread currentThread = Thread.currentThread();
  ClassLoader contextClassLoader = currentThread.getContextClassLoader();
  //在source文件夹下的自动编译
  InputStream resourceAsStream = contextClassLoader.getResourceAsStream("mysql.properties");
  BufferedInputStream bufferedInputStream = new BufferedInputStream(resourceAsStream);
  
  //读取配置文件信息创建连接
  properties.load(bufferedInputStream);
  //获取信息
  String url = properties.getProperty("url");
  String driverClass = properties.getProperty("driverClass");
  String user = properties.getProperty("user");
  String password = properties.getProperty("password");
  //获取连接 
  Connection connection = DriverManager.getConnection(url,user,password);
  return connection;
 }
 
 /**
  * 实例方法 释放资源
  * @param statement
  * @param connection
  */
 public void close(Statement statement,Connection connection,ResultSet resultSet) {
  try {
   if (resultSet!= null) {
    resultSet.close();
   }
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }finally {
   try {
    if (statement != null) {
     statement.close();
    }
   } catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
   }finally {
    if (connection != null) {
     try {
      connection.close();
     } catch (Exception e2) {
      // TODO: handle exception
      e2.printStackTrace();
     }
    }
   }
  }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值