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 = "delete from user_info";//4、写SQL语句
			if (sta.executeUpdate(sql)>0) {//5、执行语句
				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 Update {
	
	//定义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;
		} 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;
	}

	public static void main(String[] args) {
		String sql = "delete from user_info";//写SQL语句
		if(update(sql)) {//调用update(String sql)方法,传入参数
			System.out.println("YES");
		}else {
			System.out.println("NO");
		}
	}
}

猜你喜欢

转载自blog.csdn.net/IT_Helianthus/article/details/89845151