JDBC-ResultSet类和JDBCUtils工具类的详解及实现【全网最全】

ResultSet:结果集对象,封装查询结果
			* boolean next(): 游标向下移动一行,判断当前行是否是最后一行末尾(是否有数据),如果是,则返回false,如果不是则返回true
			* getXxx(参数):获取数据
				* Xxx:代表数据类型   如: int getInt() ,	String getString()
				* 参数:
					1. int:代表列的编号,从1开始   如: getString(1)
					2. String:代表列名称。 如: getDouble("balance")
			
			* 注意:
				* 使用步骤:
					1. 游标向下移动一行
					2. 判断是否有数据
					3. 获取数据

				   //循环判断游标是否是最后一行末尾。
		            while(rs.next()){
		                //获取数据
		                //6.2 获取数据
		                int id = rs.getInt(1);//第一列,指ID列
		                String name = rs.getString("name");//这里是get列的名称
		                double balance = rs.getDouble(3);
		
		                System.out.println(id + "---" + name + "---" + balance);
		            }

ResultSet类方法练习1
查询db3的account表格

import java.sql.*;

/**
 * 执行DDL语句
 */
public class JDBCDemo7 {
    
    
    public static void main(String[] args) {
    
    
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
    
    
            //1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接对象
            conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");
            //3.定义sql
            String sql  = "select * from account";
            //4.获取执行sql对象
            stmt = conn.createStatement();
            //5.执行sql
            rs = stmt.executeQuery(sql);
            //6.处理结果
            //循环判断游标是否是最后一行末尾。
            while(rs.next()){
    
    

                //获取数据
                //6.2 获取数据
                int id = rs.getInt(1);
                String name = rs.getString("name");
                double balance = rs.getDouble(3);

                System.out.println(id + "---" + name + "---" + balance);
            }

        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            //7.释放资源
            //ResultSet也要释放资源!!!

            if(rs != null){
    
    
                try {
    
    
                    rs.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }

            if(stmt != null){
    
    
                try {
    
    
                    stmt.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }

            if(conn != null){
    
    
                try {
    
    
                    conn.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }

}

在这里插入图片描述
在这里插入图片描述



ResultSet类方法练习2

定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回。
1. 定义Emp类
2. 定义方法 public List< Emp > findAll(){}
3. 实现方法 select * from emp;
在这里插入图片描述

定义一个Emp对象

import java.util.Date;

/**
 * 封装Emp表数据的JavaBean
 */
public class Emp {
    
    
    private int id;
    private String ename;
    private int job_id;
    private int mgr;
    private Date joindate;
    private double salary;
    private double bonus;
    private int dept_id;


    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getEname() {
    
    
        return ename;
    }

    public void setEname(String ename) {
    
    
        this.ename = ename;
    }

    public int getJob_id() {
    
    
        return job_id;
    }

    public void setJob_id(int job_id) {
    
    
        this.job_id = job_id;
    }

    public int getMgr() {
    
    
        return mgr;
    }

    public void setMgr(int mgr) {
    
    
        this.mgr = mgr;
    }

    public Date getJoindate() {
    
    
        return joindate;
    }

    public void setJoindate(Date joindate) {
    
    
        this.joindate = joindate;
    }

    public double getSalary() {
    
    
        return salary;
    }

    public void setSalary(double salary) {
    
    
        this.salary = salary;
    }


    public int getDept_id() {
    
    
        return dept_id;
    }

    public void setDept_id(int dept_id) {
    
    
        this.dept_id = dept_id;
    }


    public double getBonus() {
    
    
        return bonus;
    }

    public void setBonus(double bonus) {
    
    
        this.bonus = bonus;
    }


    @Override
    public String toString() {
    
    
        return "Emp{" +
                "id=" + id +
                ", ename='" + ename + '\'' +
                ", job_id=" + job_id +
                ", mgr=" + mgr +
                ", joindate=" + joindate +
                ", salary=" + salary +
                ", bonus=" + bonus +
                ", dept_id=" + dept_id +
                '}';
    }
}

实现方法:

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * * 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回。
 */
public class JDBCDemo8 {
    
    

    public static void main(String[] args) {
    
    
        List<Emp> list = new JDBCDemo8().findAll2();
        for (Emp emp : list) {
    
    
            System.out.println(emp);
        }
    }
    /**
     * 查询所有emp对象
     * @return
     */
    public List<Emp> findAll(){
    
    
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<Emp> list = null;
        try {
    
    
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");
            //3.定义sql
            String sql = "select * from emp";
            //4.获取执行sql的对象
            stmt = conn.createStatement();
            //5.执行sql
            rs = stmt.executeQuery(sql);
            //6.遍历结果集,封装对象,装载集合
            Emp emp = null;
            list = new ArrayList<Emp>();
            while(rs.next()){
    
    
                //获取数据
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");
                // 创建emp对象,并赋值
                emp = new Emp();
                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                //装载集合
                list.add(emp);
            }

        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            if(rs != null){
    
    
                try {
    
    
                    rs.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }

            if(stmt != null){
    
    
                try {
    
    
                    stmt.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }

            if(conn != null){
    
    
                try {
    
    
                    conn.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

结果:
在这里插入图片描述在while(rs.next())方法体内的id,ename等必须和数据库中的名字保持一致,但是Emp对象中的名字可以不用一致,推荐一致


_______________________________________________

由于这样每次都要连接不同数据库时,都要改动代码,代码复用性很差,此外,释放资源操作也过于冗余复杂,因此,可以使用抽取JDBC工具类 : JDBCUtils来简化代码

代码实现:
在这里插入图片描述Emp对象类的写法同上;
jdbc.properties文件:

url=jdbc:mysql:///db3
user=root
password=root
driver=com.mysql.jdbc.Driver

JDBC工具类:

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC工具类
 */
public class JDBCUtils {
    
    
    private static String url;//连接方法中要用,所以作为全局变量,使用static,static方法能用
    private static String user;
    private static String password;
    private static String driver;

    /**
     * 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
     */
    static {
    
    
        //读取资源文件,获取值。
        try {
    
    
            //1. 创建Properties集合类。
            Properties pro = new Properties();

            //获取src路径下的文件的方式--->ClassLoader 类加载器
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            URL res = classLoader.getResource("jdbc.properties");
            String path = res.getPath();
            //System.out.println(res);     //file:/F:/IdeaProjects/day11-code/out/production/day04_jdbc/jdbc.properties
            // System.out.println(path);   //D:/IdeaProjects/itcast/out/production/day04_jdbc/jdbc.properties

            //2. 加载文件
            // pro.load(new FileReader("D:\\IdeaProjects\\itcast\\day04_jdbc\\src\\jdbc.properties"));
            pro.load(new FileReader(path));

            //3. 获取数据,赋值
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");

            //4. 注册驱动
            Class.forName(driver);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
    }


    /**
     * 获取连接
     *
     * @return 连接对象
     */
    public static Connection getConnection() throws SQLException {
    
    

        return DriverManager.getConnection(url, user, password);
    }

    /**
     * 释放资源
     *
     * @param stmt
     * @param conn
     */
    public static void close(Statement stmt, Connection conn) {
    
    
        if (stmt != null) {
    
    
            try {
    
    
                stmt.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }

        if (conn != null) {
    
    
            try {
    
    
                conn.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }


    /**
     * 释放资源
     *
     * @param rs
     * @param stmt
     * @param conn
     */
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
    
    
        if (rs != null) {
    
    
            try {
    
    
                rs.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }

        if (stmt != null) {
    
    
            try {
    
    
                stmt.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }

        if (conn != null) {
    
    
            try {
    
    
                conn.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }

}

实现方法:

import cn.itcast.domain.Emp;
import cn.itcast.util.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * * 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回。
 */
public class JDBCDemo8 {
    
    

    public static void main(String[] args) {
    
    
        List<Emp> list = new JDBCDemo8().findAll2();
        for (Emp emp : list) {
    
    
            System.out.println(emp);
        }
    }
    /**
     * 演示JDBC工具类
     * @return
     */
    public List<Emp> findAll2(){
    
    
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<Emp> list = null;
        try {
    
    
           /* //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");*/
            conn = JDBCUtils.getConnection();
            //3.定义sql
            String sql = "select * from emp";
            //4.获取执行sql的对象
            stmt = conn.createStatement();
            //5.执行sql
            rs = stmt.executeQuery(sql);
            //6.遍历结果集,封装对象,装载集合
            Emp emp = null;
            list = new ArrayList<Emp>();
            while(rs.next()){
    
    
                //获取数据
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");
                // 创建emp对象,并赋值
                emp = new Emp();
                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                //装载集合
                list.add(emp);
            }

        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            /*if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }*/

            JDBCUtils.close(rs,stmt,conn);
        }
        return list;
    }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43531919/article/details/107596620
今日推荐