为了方便程序开发和代码复用,我们可以把JDBC封装到一个类,通过调用方法来获取连接,使我们的代码更加简洁。
步骤:
在静态代码中初始化
把获取连接放到一个方法中
最后关闭连接,释放资源
public class JDBCUtils {
private static String user;
private static String password;
private static String url;
private static String driver;
//在静态代码块去初始化
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty("driver");
} catch (IOException e) {
//将编译异常转成 运行异常
//调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便
throw new RuntimeException(e);
}
}
//连接数据库, 返回 Connection
public static Connection getConnection() {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//关闭相关资源
public static void close(ResultSet set, Statement statement, Connection connection) {
try {
if (set != null) {
set.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
需要配置properties文件
user=root
password=123456
url=jdbc:mysql://localhost:3306/bd01?rewriteBatchedStatements=true
driver=com.mysql.cj.jdbc.Driver
properties配置文件放在src目录下,我的配置文件是mysql.properties