JDBC 工具类封装实现
- 注册和配置都放在静态代码块完成
- 静态方法获取连接,和释放资源
- 本类不产生实例
- 5版本 + 已经可以实现无驱动注册,所以驱动部分注释了
package cn.dai.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; /** * @author ArkD42 * @file Jdbc * @create 2020 - 04 - 23 - 19:25 */ public class JdbcUtil { // 不可生成实例 private JdbcUtil(){} // 连接对象,扩大作用域 private static Connection connection; static { InputStream inputStream = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); try { properties.load(inputStream); // String driverClass = properties.getProperty("driverClass"); String url = properties.getProperty("url"); String user = properties.getProperty("user"); String password = properties.getProperty("password"); // Class.forName(driverClass); connection = DriverManager.getConnection(url, user, password); // System.out.println(connection); 打印检查 } catch (Exception e) { e.printStackTrace(); } } /** * 获取连接 * @return 返回连接对象 */ public static Connection getConnection(){ return connection; } /** * 释放资源关闭连接 * @param connection 连接对象 * @param preparedStatement 预编译SQL对象 */ public static void closeResource(Connection connection, PreparedStatement preparedStatement){ try { if (preparedStatement != null) preparedStatement.close(); if (connection != null) connection.close(); }catch (SQLException e){ e.printStackTrace(); } } }