带配置文件的工具类
public class DBUtil {
//声明成成员变量 方便使用
private static Connection connection;
private static String driverClass;
private static String url;
private static String username;
private static String password;
static {
readFile();
//注册驱动
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//读文件的方法
public static void readFile() {
//读文件
//类加载器 直接获取bin文件夹下的该文件
InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties=new Properties();
try {
properties.load(inputStream);
driverClass= properties.getProperty("driverClass");
url= properties.getProperty("url");
username= properties.getProperty("username");
password= properties.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
//获取连接方法
public static Connection getConnection() {
try {
connection=DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("获取连接失败");
}
return connection;
}
}
public class DBUtil {
//声明成