一、优化前的JDBC增删改代码
优化之前的代码如下(这里以增删改中添加数据为例,因为它们除了sql语句不同以外其它相同):
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement sta = null;
try {
Class.forName("com.mysql.jdbc.Driver");
//1、加载驱动
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
//2、建立连接
sta = con.createStatement();
//3、创建SQL语句对象
String sql = "inset into user_info(id,name) values('123','Jim')";
//4、写SQL语句
if (sta.executeUpdate(sql)>0) {
//5、执行sql语句
System.out.println("添加成功!");
}else {
System.out.println("添加失败!");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//6、释放资源
try {
if (sta!=null) {
sta.close();
}
} catch (SQLException e) {
e.printStackTrace();
}try {
if (con!=null) {//
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
上述优化前代码虽然也能够实现增删改的功能,但是每次需要实现该功能时,就必须将实现过程代码重新写一遍,这样的话代码的复用性很差。所以为了解决该问题,就需要利用Java的三大特征之一的封装去定义一个方法,将该功能的实现过程封装到该方法中,以便调用。
二、优化后的代码
public class Test {
//定义update(String sql)方法,将增删改的具体实现过程封装到该方法中,以后如果要实现该功能,调用该方法即可
public static boolean update(String sql) {
Connection connection = null;
Statement statement= null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
statement= connection.createStatement();
return statement.executeUpdate(sql)>0;
//定义该方法的返回值为Boolean类型,所以需要使用return返回statement.executeUpdate(sql)>0的值
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (statement!=null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
//如果没有执行sql语句,则返回false
}
public static void main(String[] args) {
String sql = "inset into user_info(id,name) values('123','Jim')";
//写SQL语句
if(update(sql)) {
//调用定义好的update方法
System.out.println("YES");
}else {
System.out.println("NO");
}
}
}
总结:优化后的代码将增删改功能定义在了update(String sql)方法中,那么每次需要执行增删改功能时,只需要定义一个sql语句并调用update方法就可以了