1.把创建Connection数据库连接对象的代码,抽取到Util工具类中,并提供方法getConn用于向调用者返回Connection对象即可。
2.把Class.forName("com.mysql.jdbc.Driver")加载注册驱动,抽到Util工具类,并且放到静态代码块中,每次类加载而执行,只执行一次。
3.把关闭资源的代码,抽取到Util工具类中。
4.把连接数据库的连接地址rul,账号name,密码password,以及其他属性,放到项目路径下的配置文件db.properties中。
(1)db.properties
(2)项目路径下的配置文件db.properties 获取过程:
1) 获取类加载器:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
2)使用类加载器获取项目 类路径下面的文件:
InputStream inputStream = classLoader.getResourceAsStream("db.properties");
3)使用Properties加载配置文件对应的输入流
Properties p=new Properties();
p.load(inputStream);
4) 通过p.getProperty("配置文件中对应的key") 获取配置文件的值。
具体代码:
public class JdbcUtil { // alt+shif+a 多行修改,修改以后还原 alt+shif+a /*private static String driverClassName = "com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/jdbcdemo"; private static String username = "root"; private static String password = "root";*/ private static Properties p = new Properties(); static { try { //1.获取类加载器 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); //2,使用类加载器获取项目 类路径下面的文件 InputStream inputStream = classLoader.getResourceAsStream("db.properties"); //3.使用Priperties加载配置文件对应的输入流 p.load(inputStream); Class.forName(p.getProperty("driverClassName")); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() { try { return DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password")); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("亲,连接数据库失败", e); } } public static void close(Connection conn,PreparedStatement ps,ResultSet rs) { try { if(rs !=null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); }finally { try { if(ps !=null) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); }finally { try { if(conn !=null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } }