封装JDBCUtils工具类

封装JdbcUtils的工具类

  1. 将getConnection()和close()方法封装进去
  2. getConnection()方法用于创建程序与数据库的连接 *
  3. close()方法用于释放资源
  4. 将成员变量定义的数据放入配置文件(properties格式)中,因此我们在修改数据时不需要进去源程序,可以直接在配置文件中修改
  5. //创建成员变量
    private static String url;
    private static String username;
    private static String password;
    private static String driverPath;
static {
    try {
        //读取配置文件中的数据
        ClassLoader classLoader = JdbcUtils.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("data.properties");

        //创建properties对象读取流中的数据
        Properties properties = new Properties();
        properties.load(is);
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        driverPath = properties.getProperty("driverPath");

        //一定要记住关闭流
        is.close();

        //注册驱动
        Class.forName(driverPath);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public static Connection getConnection() throws SQLException {
    //创建连接对象
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
}

public static void close(Connection conn, Statement stm, ResultSet res) throws SQLException {
    if (conn != null) {
        conn.close();
    }
    if (stm != null) {
        stm.close();
    }
    if (res != null) {
        res.close();
    }
}

public static void close (Connection conn,Statement stm) throws SQLException {
    close(conn,stm,null);
}

你可能感兴趣的:(Java)