1、使用类的加载器来加载database.properties文件流。
2、读取配置文件,获取连接,只执行一次,static{ }
3、JDBCUtils封装类
package cn.itcast.jdbcutils; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; public class JDBCUtils { public static Connection con; private static String driverClass; private static String url; private static String username; private static String password; public JDBCUtils(){}; //定义静态方法,返回数据库的连接对象 static{ try{ readConfig(); // 1注册驱动 Class.forName(driverClass); con = DriverManager.getConnection(url, username, password); }catch(Exception ex){ throw new RuntimeException(ex+" 数据库连接失败!"); } } //获取连接 public static Connection getConnection(){ return con; } private static void readConfig() throws IOException{ // 2、获取配置文件流,读取文件信息,获取连接 //使用类的加载器加载database文件 InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("database.properties"); Properties pro = new Properties(); pro.load(in); //System.out.println(pro); //获取集合中的键值对 String driverClass = pro.getProperty("driverClass"); String url = pro.getProperty("url"); String username = pro.getProperty("username"); String password = pro.getProperty("password"); } public static void close(Connection con,ResultSet rs,PreparedStatement ps){ if(rs != null){ try{ rs.close(); }catch(SQLException ex){} } if(ps != null){ try{ ps.close(); }catch(SQLException ex){} } if(con != null){ try{ con.close(); }catch(SQLException ex){} } } public static void close(Connection con,PreparedStatement ps){ if(ps != null){ try{ ps.close(); }catch(SQLException ex){} } if(con != null){ try{ con.close(); }catch(SQLException ex){} } } }