public class JdbcUtil {
private static String url = null;
private static String user =null;
private static String password = null;
static {
try {
//只要JdbcUtil类加载了,就会执行静态代码块中的代码
//读取配置文件中的信息:properties文件
//Properties类表示一组持久的属性。 Properties可以保存到流中或从流中加载。
// 属性列表中的每个键及其对应的值都是一个字符串。
Properties properties = new Properties();
properties.load(new FileInputStream("src/db.properties"));
//数据都在properties 对象中
String diver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Class.forName(diver);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection () {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//关闭资源
//增删改 需要关闭两个 查 关闭三个
public static void close (Connection connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close (Statement statement, Connection connection) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close (ResultSet resultSet, Statement statement, Connection connection) {
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}