首页 > 其他分享 >JDBC练习select语句和JDBC工具类

JDBC练习select语句和JDBC工具类

时间:2022-10-21 11:55:06浏览次数:53  
标签:语句 JDBC rs int public emp new id select

JDBC练习-select语句

定义一个方法,查询emp表中的数据将其封装为对象,然后装载集合,然后打印

1.定义emp类

2.定义方法public List<Emp> findAll(){}

3.实现方法select * from emp;

Emp类

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;

    //toString
    @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 +
                '}';
    }

    //get和set
    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 double getBonus() {
        return bonus;
    }

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

    public int getDept_id() {
        return dept_id;
    }

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

测试类:

    public static void main(String[] args) {
        List<Emp> all = new JdbcPractice6().findAll();
        for (Emp emp : all) {
            System.out.println(emp);
        }
    }


    /**
     * 查询所有emp对象
     * @return
     */
    public List<Emp> findAll(){
        Connection conn = null;
        Statement state = null;
        ResultSet rs =null;
        List<Emp> list = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");
            //3.定义sql
            String sql = "select * from emp";
            //4.获取执行sql对象
            state = conn.createStatement();
            //5.执行sql(结果集对象)
            rs = state.executeQuery(sql);
            //6.遍历结果集,封装对象,装载集合
            Emp emp= null;
            list = new ArrayList<>();
            while (rs.next()){
                //6.1获取数据
                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) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if (rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (state != null){
                try {
                    state.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return list;
    }

 

 

JDBC工具类

 抽取工具类:JDBCUtils

  目的:简化书写

  分析:

    1.注册驱动  

    2.抽取一个方法获取连接对象

      需求:不想传递参数(麻烦),还得保证工具类的通用性。

      解决:配置文件

        jdbc.properties

         url = 

         user =

         password =

    3.抽取一个方法释放资源

 JDBCUtils工具类

/**
 * JDBC工具类
 *
 */
public class JDBCUtils {
    //声明三个成员变量
    private static String url;// 连接数据库
    private static String user;// 用户名
    private static String password;// 密码
    private static String driver;// 连接驱动
    /**
     *  文件的读取,只需要读取一次即可拿到这些值,使用静态代码块(工具类静态块)
     */
    static {
        //读取资源文件,获取值
        try {
            //1.创建Properties集合类
            Properties prop = new Properties();
            //2.加载文件
            prop.load(new FileReader("src/main/resources/jdbc.properties"));
            //3.获取数据,赋值(于配置文件中的属性名要一致)
            url = prop.getProperty("url");
            user = prop.getProperty("user");
            password = prop.getProperty("password");
            driver = prop.getProperty("driver");
            //注册驱动
            Class.forName(driver);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *  获取连接
     * @return 连接对象
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    /**
     * 释放资源
     * @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();
            }
        }

    }
}

测试类

    public static void main(String[] args) {
        //创建方法引用方法
        List<Emp> all = new JdbcPractice7().findAll2();
        for (Emp emp : all) {
            System.out.println(emp);
        }
    }


    /**
     * 查询所有emp对象
     * @return
     */
    public List<Emp> findAll2(){
        Connection conn = null;
        Statement state = null;
        ResultSet rs =null;
        List<Emp> list = null;
        try {
//            //1.注册驱动
//            Class.forName("com.mysql.cj.jdbc.Driver");
//            //2.获取连接
//            conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");
            conn = JDBCUtils.getConnection();
            //3.定义sql
            String sql = "select * from emp";
            //4.获取执行sql对象
            state = conn.createStatement();
            //5.执行sql(结果集对象)
            rs = state.executeQuery(sql);
            //6.遍历结果集,封装对象,装载集合
            Emp emp= null;
            list = new ArrayList<>();
            while (rs.next()){
                //6.1获取数据
                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) {
            throw new RuntimeException(e);
        }finally {
            //释放资源
            JDBCUtils.close(rs, state, conn);
        }
        return list;
    }

 

标签:语句,JDBC,rs,int,public,emp,new,id,select
From: https://www.cnblogs.com/qihaokuan/p/16812991.html

相关文章

  • Jmeter----请求的reponse结果中的某个参数作为JDBC Request的查询条件
    一、前言数据库连接成功二、需求将登录账号12608523691,接口的reponse的参数uuid作为JDBCRequest的查询条件   二、添加后置处理器并进行相关的设置。......
  • Java I/O(4):AIO和NIO中的Selector
    您好,我是湘王,这是我的博客园,欢迎您来,欢迎您再来~ 在Java NIO的三大核心中,除了Channel和Buffer,剩下的就是Selector了。有的地方叫它选择器,也有叫多路复用器的(比如Netty)。......
  • C语言多路开关模式的switch语句
    C语言多路开关模式的switch语句将switch语句中有的语句块的break删除掉。使多个语句块输出同一个。例子:输入一个月份,判断是几月份。#define_CRT_SECURE_NO_WARNINGS1#incl......
  • if ... else和switch语句用法
    关于ifelse和switch语句用法:if...else语句:判断条件为真时则执行语句1;否则执行elseif(判断表达式){语句1;}else{语句2;}switch语句:可以有多种选择。switch(表达式){case情况1:语......
  • C语言中的分支语句——if和switch语句
    一.什么是语句C语言中由一个分号‘;’隔开的就是一条语句。比如:    printf("haha\n");    1+2;再比如:    intmain()    {     ......
  • C语言循环语句——while、for、do while
    一.while循环    我们已经学会了if语句,当条件满足的情况下,if语句后的语句执行,否则不执行。但是这个语句只会执行一次。但是我们发现生活中很多的实际的例子是∶同......
  • sql语句排序无效的问题
    数据可视化时因为数据类型排序无效的问题:这是由于你要排序的类型是String类型的而ORDERBY方法排序要求整数型。这就需要在ORDERBY后加CAST(需要排序的字段A......
  • shell条件语句
    一,条件测试1.test命令测试表达式是否成立,若成立返回0,否则返回其他数值格式1:test条件表达式格式2:[条件表达式][root@localhost~]#test-e1.txt|echo$......
  • SpringJDBC 练习2
    1,查询id为1的记录,将其封装为Map集合2,查询所有记录 将其封装为List 3,查询所有记录 将其封装为Emp对象的List集合 4,查询总记录数......
  • Spring JDBC 练习
    1,修改1号数据的salary为100002,添加一条记录3,删除刚才添加的数据 ......