优点:
- 便于修改连接属性。只需在配置文件中修改,不需要在代码中修改了。
- 更易于维护代码安全性。
方法:
- 在src文件嘉下创建database.properties文本文件;添加内容:
driver = com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/y1 name=root password=root
- 创建工具类MyJDBCUtiles.java,添加代码:
package com.kong.JDBCUtils; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class MyJDBCUtiles { private MyJDBCUtiles(){} private static Connection con; private static String driver; private static String url; private static String name; private static String password; static{ try { InputStream is = MyJDBCUtiles.class.getClassLoader().getResourceAsStream("database.properties"); Properties properties = new Properties(); properties.load(is); driver = properties.getProperty("driver"); url = properties.getProperty("url"); name = properties.getProperty("name"); password = properties.getProperty("password"); Class.forName(driver); con = DriverManager.getConnection(url, name, password); }catch (Exception ep){ throw new RuntimeException(ep+"数据库连接失败"); } } public static Connection getConnection(){ return con; }
- 其他类使用时调用即可
Connection con = MyJDBCUtiles.getConnection(); System.out.println(con);
- 输出结果
完美^_^