JDBC之代码重构以使代码更简洁

首先在我们常用的包下再新建一个java文件JDBCUtils。作为我们的工具包
在这里插入图片描述
然后再这个包中的代码为一系列我们无论干什么总是会用到的函数
例如连接函数和关闭函数等

package jdbc.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class JDBCUtils {
	//这三个常用的量,放在上面,想改的话直接就改了。
	private static final String connectionURL="jdbc:mysql://localhost:3306/hahahhha?useUnicode=true&characterEncoding=UTF8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT";
	private static final String username="root";
	private static final String password="password";
	
	//建立连接的通用函数,声明为static,方便别的java文件直接通过类名.方法名直接调用。
	public static Connection getConnection(){
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			return DriverManager.getConnection(connectionURL,username,password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//使用什么驱动连接数据库
		return null;
	}
	
	//关闭资源的通用函数
	public static void close(Connection con,Statement stmt,ResultSet rs) {
		closeResultSet(rs);
		closeStatement(stmt);
		closeConnection(con);
	}
	//再写一个参数不同的函数,用于关闭有两个Statement时且无rs时,比如转账情况
	public static void close(Connection con,Statement stmt1,Statement stmt2) {
		closeStatement(stmt1);
		closeStatement(stmt2);
		closeConnection(con);
	}
	private static void closeResultSet(ResultSet rs) {
		try {
			if(rs!=null) rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static void closeStatement(Statement stmt) {
		try {
			if(stmt!=null) stmt.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static void closeConnection(Connection con) {
		try {
			if(con!=null) con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


这样的话向我们之前的selectAll()函数就可以改写为:

	public static void SelectAll() {
		Connection con=null;
		Statement stmt=null;
		ResultSet rs=null;
		try {
			con=JDBCUtils.getConnection();//运用Utils工具包中的方法重构,用以简化我们的代码量
			stmt=con.createStatement();
			rs=stmt.executeQuery("select * from student");
			while(rs.next())
			{
				System.out.println(rs.getString(1)+","+rs.getString(2));
				System.out.println(rs.getString("xuehao")+","+rs.getString("xingming"));
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			
				JDBCUtils.close(con, stmt, rs);
		}
	}

是不是很简洁?

猜你喜欢

转载自blog.csdn.net/henulmh/article/details/105050444