代码改进背景介绍:V2版本
如果将数据库连接信息放在代码中不利于后期的维护与查找,为了解决这个问题,我们可以使用java提供的API工具类:
java.util.Properties来实现。
首先通过下面的简单实例了解如何使这个工具类:
项目结构如下图所示:
1.在resources目录下编写数据库连接属性文件db.properties:【注意:这里使用:与=效果一样】
jdbc.driverclass=oracle.jdbc.driver.OracleDriver jdbc.url:jdbc:oracle:thin:@localhost:1521:orcl jdbc.user=learn jdbc.password=learn2.编写Properties测试类TestProperties:
/** * 演示:Properties工具类读取属性文件 * @author Cher_du * */ public class TestProperties { public static void main(String[] args) throws IOException { Properties prop =new Properties(); //获取指向当前项目类路径中属性文件的输入流 InputStream inStream = TestProperties.class.getClassLoader() .getResourceAsStream("db.properties"); //加载属性文件数据到内存中 prop.load(inStream); //根据已知的key获取value String url = prop.getProperty("jdbc.url"); System.out.println(url); } }
3.运行程序我们可以看到成功获取到对应属性url信息
正式开工:
通过上面对Properties类的简单介绍,下面通过它来改进我们之前的DBUtil工具类:
/** * 该类用来管理连接 * 数据库连接的信息,保存在属性文件中 * @author Cher_du * */ public class DBUtil2 { private static String driverClass; private static String url; private static String user; private static String password; static{ //加载属性文件数据 Properties prop = new Properties(); try { prop.load(DBUtil2.class.getClassLoader().getResourceAsStream("db.properties")); driverClass = prop.getProperty("jdbc.driverclass"); url = prop.getProperty("jdbc.url"); user = prop.getProperty("jdbc.user"); password = prop.getProperty("jdbc.password"); //1.加载驱动 Class.forName(driverClass); }catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException("加载驱动错误!",e); }catch (IOException e) { e.printStackTrace(); throw new RuntimeException("读取属性文件错误!",e); } } //2.创建连接 /*如何定义一个创建连接的方法 * * 返回值类型: * 是否有运算结果,如果有, * 结果的类型即为返回值类型。 * 参数列表: * 功能中,是否有不确定的数据参与运算 * 如果有,即为参数列表 */ public static Connection getConnection() throws SQLException{ Connection conn = DriverManager.getConnection(url, user, password); return conn; } //3. public static void close(Connection conn){ if(conn !=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException("关闭连接错误!",e); } } } //测试 public static void main(String[] args) throws SQLException { System.out.println(getConnection()); } }
运行程序可以看到成功获取到数据库连接!