JDBC快速入门(三) 代码再优化

会用简单的JDBC进行查询之后我们就要去封装代码去进行更高级的操作

1.封装select查询语句

2.JDBC工具类

1.封装select查询语句
我们在这里新建了一个数据库,下面我们将查询students里的所有数据,封装成对象,然后装载集合,返回。
数据库信息

  1. 定义students类
  2. 定义方法public List<students> findAll(){ }
  3. 实现方法select * from students

定义students类
我们新建一个包com.byzhang.domain,并在里边新建一个类students.java作为bean对象
bean对象

该bean用来封装students的数据
students.java内容如下所示

package com.byzhang.domain;

public class students {
    private int id;
    private String name;
    private double score;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "students{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}

定义方法public List<student> findAll(){ }
我们在JDBC中新建一个JdbcDemo4,并定义一个findAll()方法
具体代码如下:main方法是测试作用

package com.byzhang.jdbc;

import com.byzhang.domain.students;

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

public class JdbcDemo4 {
    //查询所有students对象
    public static void main(String[] args) {
        List<students> list = new JdbcDemo4().findAll();
        System.out.println(list);
    }

    public List<students> findAll(){
        Connection conn = null;
        Statement stmt = null;
        ResultSet res = null;
        students stu = null;
        List <students> list = new ArrayList<students>();
        try{
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取Connection对象
            conn = DriverManager.getConnection("jdbc:mysql:///test?useSSL=false","root","123456");
            //3.定义sql语句
            String sql = "select * from students";
            //4.获取执行对象
            stmt = conn.createStatement();
            //5.执行sql
            res = stmt.executeQuery(sql);
            //6.处理结果
            while(res.next()){
                //获取数值
                int id = res.getInt(1);
                String name = res.getString(2);
                double score = res.getDouble(3);
//                System.out.println(id+"->"+name+"->"+score);
                stu = new students();
                //封装对象
                stu.setId(id);
                stu.setName(name);
                stu.setScore(score);
                //装载集合
                list.add(stu);
            }
        }catch (ClassNotFoundException | SQLException e){
            e.printStackTrace();
        }finally {
            if(res != null){
                try{
                    res.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;
    }
}

2.工具类
我们在写代码的时候发现,我们代码的重复度相当的高,很多很多重复写的代码,于是我们可以抽取一个DJBCutils的工具类来简化书写
我们新建一个utils包还有JdbcUtils类
utils
并在src目录下面新建一个jdbc.properties
目的是吧url username password这些参数写到配置文件里边,方便改写
jdbc.properties
配置文件
JdbcUtils.java内容如下,里边内容较多,写了注释

package com.byzhang.utils;

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

public class JdbcUtils {
    private static String url;
    private static String name;
    private static String password;
    private static String driver;
    /*
    * 文件的读取只需要读取一次就可以一直拿来用,就使用静态代码块
    * */
    static{
        //读取资源文件,获取值

        try {
            //1.创建properties集合类
            Properties pro = new Properties();
            //2.加载文件

            //获取src目录下的文件的方法ClassLoader类加载器
            ClassLoader classloader = JdbcUtils.class.getClassLoader();
            URL resource = classloader.getResource("jdbc.properties");
            String path = resource.getPath();
            pro.load(new FileReader(path));
            //3.加载数值,赋值
            url = pro.getProperty("url");
            name = pro.getProperty("name");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
            //4.注册驱动
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        //加载数据,赋值
    }



    //获取链接
    //返回链接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,name,password);
    }

    public static void close(Statement stmt,Connection conn) {
        if(stmt != null) {
            try{
                stmt.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }

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

    public static void close(ResultSet res, Statement stmt, Connection conn) {
        if(res != null) {
            try{
                res.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }

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

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

测试Java类如下,

package com.byzhang.jdbc;

import com.byzhang.domain.students;
import com.byzhang.utils.JdbcUtils;
import com.sun.jndi.toolkit.ctx.StringHeadTail;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class JdbcDemo5 {

    public static void main(String[] args) {
        List<students> list = new JdbcDemo5().findAll();
        System.out.println(list);
    }

    public static List<students> findAll(){
        Connection conn = null;
        Statement stmt = null;
        ResultSet res = null;
        List<students> list = new ArrayList<students>();
        students stu = new students();
        try{
            //注册驱动获取链接
            conn = JdbcUtils.getConnection();
            //获取执行对象
            stmt = conn.createStatement();
            //定义sql
            String sql = "select * from students";
            //执行sql
            res = stmt.executeQuery(sql);
            //处理结果
            while(res.next()){
                int id = res.getInt(1);
                String name = res.getString(2);
                double score = res.getDouble(3);

                stu = new students();

                stu.setId(id);
                stu.setScore(score);
                stu.setName(name);

                list.add(stu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.close(res,stmt,conn);
        }
        return list;
    }
}

通过对比可以发现,代码不再像以前那么臃肿了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值