JDBCUtils that satisfies the opening and closing principle~

We all know that the open-close principle means that it is closed to modifications and open to expansion. So for the implementation to be able to connect to the database through DriverManager or use c3P0 to connect to the database, we only need to use 连接数据库的方式即为可变点abstract classes or interfaces to encapsulate variable points , and then Each specific implementation of a variable point is described by a class

Encapsulate variable points: get the connection object

package JDBC;

import java.sql.Connection;
import java.sql.SQLException;

public  abstract  class AbstractJDBCUtils {
    
    
    public abstract Connection getConnection() throws SQLException;//用于定义获取连接对象的抽象方法
    //关闭资源的方法
    .........
}

Specific implementation method 1: Obtain the connection object through the c3p0 database connection pool

package JDBC;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCFromC3p0Source extends AbstractJDBCUtils{
    
    
    //通过使用c3p0获取连接对象的方法
    .......
    }
}

Specific implementation method 2: Obtain the connection object through DriverManager

package JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCFromDriverManager extends AbstractJDBCUtils{
    
    
    @Override
    public Connection getConnection() throws SQLException {
    
    
       //通过DriverManager获取连接对象的方法
    }
}

Guess you like

Origin blog.csdn.net/m0_64365419/article/details/133142292