将连接数据库的加载驱动和获取连接、关闭连接放入一个工具包当中,方便操作
public Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
//1.通过本类的类加载器读取配置文件中的四个基本信息
InputStream is = ClassLoader.getSystemResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//2.加载驱动
Class.forName(driverClass);
//3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
//关闭连接和statement
public void closeResource(PreparedStatement ps,Connection conn){
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (conn!=null)
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}