java---耦合和解耦

java---耦合和解耦

package com.itheima.jdbc;

/*
 * 程序的耦合
 *      耦合:程序间的依赖关系
 *          包括:
 *              类之间的依赖
 *              方法间的依赖
 *      解耦:
 *          降低程序间的依赖关系
 *      时间开发中,应该做到:
 *          编译期不依赖,运行时才依赖
 *      解耦的思路:
 *          1. 使用反射创建对象,避免使用new关键字
 *          2. 通过读取配置文件来获取要创建的对象全限定类名
 */

import java.sql.*;

public class JdbcDemo1 {
    public static void main(String[] args) throws Exception {
        //-----------------------------------------------------
        // 1. 注册驱动,如果没有这个包/驱动,那么编译期就会报错。就是程序的耦合。
        // DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        Class.forName("com.mysql.jdbc.Driver");
        //-----------------------------------------------------
        // 2. 获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxx", "xxx", "123");
        // 3. 获取操作数据库的预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement("select * from auth_user");
        // 4. 执行sql,得到结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        // 5. 便利结果集
        while (resultSet.next()) {
            System.out.println(resultSet.getString("first_name"));
        }
        // 6. 释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章