新建一个Java类,取名为DBUtils,里边一个静态代码块,两个静态方法。
static { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public static Connection getConnection() { Connection conn = null; //数据库连接字符串 String url = "jdbc:sqlserver://localhost:1433;databaseName=StudentManage"; try { //获取连接对象 conn = DriverManager.getConnection(url, "sa", "sql2012"); } catch (SQLException sqlException) { sqlException.printStackTrace(); } return conn; }
public static void closeDb(Connection conn, Statement sm, ResultSet rs) { try { if (conn != null) { conn.close(); } if (sm != null) { sm.close(); } if (rs != null) { rs.close(); } } catch (SQLException sqlException) { sqlException.printStackTrace(); } }
以上重构方案虽然将连接数据库可重用性代码提取出来做成JDBC工具类,但是整体耦合度还是相对较高,比如、数据库连接字符串,用户名,登录密码这些值都是写死在Java类中。
dirver = com.microsoft.sqlserver.jdbc.SQLServerDriver url = jdbc:sqlserver://localhost:1433;databaseName=StudentManage user = sa passwrod = sql2012
private static final ResourceBundle resourceBundel; private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
static { //加载配置文件 resourceBundel = ResourceBundle.getBundle("jdbc"); try { //从配置文件中获取dirver的值 Class.forName(resourceBundel.getString("dirver")); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public static Connection getConnection() { //直接从连接中获取 Connection connection = threadLocal.get(); try { //判断是否为null if (connection == null) { //创建连接对象 //里边的参数都从配置文件中读取 connection = DriverManager.getConnection(resourceBundel.getString("url"), resourceBundel.getString("user"), resourceBundel.getString("password")); //方法到连接池 threadLocal.set(connection); } } catch (SQLException sqlException) { sqlException.printStackTrace(); } return connection; }
这样,不管是修改数据库还是登录密码,只需在配置文件中修改接口,无需变动Java代码。更不需要从新编译。概括来讲、就是要通过一些重构方案,降低代码的耦合度,从而提高代码的可扩展性。