工具类的作用:封装加载驱动,获取链接,释放资源
这个工具类包括数据库连接,资源管理,查询操作等功能
类加载时的加载驱动:将class.forName("com.mysql.jdbc.Driver")代码有第一次加载的时候执行一次就不再执行了,只需加载一次,不需重复加载
jdbc工具类代码:
private static String driver; private static String url; private static String username; private static String password; static { InputStream is=null; try { is=jdbcutils.class.getClassLoader().getResourceAsStream("jdbc"); Properties properties=new Properties(); properties.load(is); driver=properties.getProperty("driver"); url=properties.getProperty("url"); password=properties.getProperty("password"); username=properties.getProperty("username"); System.out.println(driver); System.out.println(password); System.out.println(username); System.out.println(url); } catch (Exception e) { throw new RuntimeException(e); }finally { if (is!=null){ try { is.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } public static Connection getConnection() throws SQLException, ClassNotFoundException { Class.forName(driver); Connection connection= DriverManager.getConnection(url,password,username); return connection; } public static void clo(ResultSet resultSet, Statement statement, Connection connection) throws SQLException { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } }