代码:
public class JDBCUtilsConfig {
private static Connection con;
private static String driverClass;
private static String url;
private static String userName;
private static String password;
static{
try {
readConfig();
Class.forName(driverClass);
con = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException | IOException | SQLException e) {
throw new RuntimeException("数据库连接失败");
}
}
private static void readConfig() throws IOException{
InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro = new Properties();
pro.load(in);
driverClass = pro.getProperty("driverClass");
url = pro.getProperty("url");
userName = pro.getProperty("username");
password = pro.getProperty("password");
}
public static Connection getConnection(){
return con;
}
}
其中
JDBCUtilsConfig.class是获得当前对象所属的class对象
getClassLoader()是取得该Class对象的类装载器
getResourceAsStream(“database.properties”) 调用类加载器的方法加载 资源,返回的是字节流
使用Properties类是为了可以从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象,然后通过getProperty方法用指定的键在此属性列表中搜索属性
Class.forName(driverClass);注册驱动