public class JdbcUtils {
//方法一
private static DruidDataSource dataSource;
static {
try {
Properties properties = new Properties();
// 读取 jdbc.properties 属性配置文件
InputStream inputStream =
JdbcUtils.class.getClassLoader().getResourceAsStream("user.properties");
// 从流中加载数据
properties.load(inputStream);
// 创建 数据库连接 池
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接池中的连接
* @return 如果返回 null,说明获取连接失败
有值就是获取连接成功
*/
public static Connection get_connection(){
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//方法二
public static Connection get_connection() {
String path= "user.properties";
Connection connection = null;
InputStream is = null;
try {
Properties pro = new Properties();
is = JdbcUtils.class.getClassLoader().getSystemResourceAsStream("user.properties");
pro.load(is);
DataSource dataSource = DruidDataSourceFactory.createDataSource(pro);
connection = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return connection;
}
结果就是第二种方法会报空指针异常
![图片说明](https://img-ask.csdn.net/upload/202008/27/1598496713_753949.png)
求大佬解答两种方法有什么区别