我们知道封装的意义处理降低耦合 还有就是可以将重复的代码变成一个可以随时调用的方法 减少代码量 而我们的jdbc操作就有许多重复的代码时每次都需要写的
如:
- 注册驱动
- 获得连接
- 释放资源
我们发现除了获取数据库操作对象和执行sql语句外 我们所有的操作都是 一成不变的 所以为了方便我们使用 我们将那些重复的操作可以写在一个指定的类中 在我们操作数据库时直接调用该类中对应的方法即可
示例:
public class jdbc_utils {
static String url;
static String user;
static String pwd;
//注册驱动
static {//因为写在静态代码块里 所以在调用该类时就会自动执行代码块中的内容
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src\\mysql.properties"));
url = properties.getProperty("url");
user = properties.getProperty("user");
pwd = properties.getProperty("pwd");
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//与数据库进行连接
public Connection getConnection(){
try {
return DriverManager.getConnection(url,user,pwd);
} catch (SQLException e) {
throw new RuntimeException(e);
}
};
//关闭连接
//因为我们有可能用不上所有对象 所以我们只需要关闭使用的对象即可
//resultSet对象就是如此 我们只有执行查询操作的时候才会用到他
public void close(Connection connection, ResultSet resultSet, Statement statement){
try {
if (connection!=null){
connection.close();
}
if (resultSet!=null){
resultSet.close();
}
if (statement!=null){
statement.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
而之后我们只需要在执行 注册驱动 ,获得连接, 释放资源 时调用该类中指定的方法即可:
public class jdbc_utils_DML {
public static void main(String[] args) throws SQLException {
String sql="insert into admin values(1,tom)";
//获得与数据库的连接
Connection connection = new jdbc_utils().getConnection();
//获取数据库操作对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//执行sql语句
preparedStatement.executeUpdate();
//释放资源
new jdbc_utils().close(connection,null,preparedStatement);
}
}
这样jdbc操作就会变得更加方便 重复的代码不再需要重复写