在代码当中的话,关于驱动,url,user和userpasssword都是变化的,最初的代码是如下这样子:
/** *@Description: <br> * 〈公共连接数据库的方法〉 * @Param: [] * @Return: java.sql.Connection * @Author: * @Date: */ public static Connection getConnection() throws SQLException { Connection con=null; try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } con= DriverManager.getConnection( "jdbc:mysql://localhost:3306/student_jpa?serverTimezone=UTC", "Kang", "qwerty" ); return con; }
如果说使用一个数据库还好,不用随意改动代码,如果说要使用oracle数据库,这时我们就用到了配置文件jdbc.properties。
在项目resource包下创建jdbc.properties:如下
#属性文件中不要写空行,不要空格 className=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/student_jpa?serverTimezone=UTC username=Kang userpassword=qwerty
这时候连接数据库的方法可以这样写:如下
//用属性文件的工具类读取属性文件的内容 private static PropertyUtil pu=new PropertyUtil("jdbc.properties"); private static String className=pu.getValue("className"); private static String url=pu.getValue("url"); private static String username=pu.getValue("username"); private static String userpassword=pu.getValue("userpassword"); /** *@Description: <br> * 〈公共连接数据库的方法〉 * @Param: [] * @Return: java.sql.Connection * @Author: * @Date: */ public static Connection getConnection() throws SQLException { Connection con=null; try { Class.forName(className); } catch (ClassNotFoundException e) { e.printStackTrace(); } con= DriverManager.getConnection(url,username,userpassword); return con; }
这样子一来就算换数据库,只要把配置文件当中的相关值换掉就可以啦!