JDBC——实现对数据进行CRUD操作一

实现对数据的CRUD操作

CRUD即增删改查,我们将这四种操作分为两类,一类是增删改,无返回值,一类是查询,有返回值,我们先来看一下增删改

  • 插入数据

    1. 获取配置文件
    2. 读取配置文件信息
    3. 注册驱动,连接数据库
    4. 预编译sql,返回PreparedStatement的实例
    5. 填充占位符
    6. 执行sql
    7. 关闭资源
     @Test
        public void insertTest() throws Exception{
            //1.获取配置文件
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
            //2.读取配置文件信息
            Properties properties = new Properties();
            properties.load(is);
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String url = properties.getProperty("url");
            String driverClass = properties.getProperty("driverClass");
            //3.注册驱动,连接数据库
            Class.forName(driverClass);
            Connection connection = DriverManager.getConnection(url, user, password);
            //4.预编译sql,返回PreparedStatement的实例
            String sql = "insert into customers(name,email,birth) values (?,?,?)";   //?代表占位符
            PreparedStatement ps = connection.prepareStatement(sql);
            //5.填充占位符
            ps.setString(1,"秦始皇");
            ps.setString(2,"qinshihuang@162.com");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date date = sdf.parse("1003-04-12");
            ps.setDate(3,new Date(date.getTime()));
            //6.执行sql
            ps.execute();
            //7.关闭资源
            ps.close();
            connection.close();
        }
    
  • 更新数据

    我们发现之前使用增加数据的方法尤为繁琐,尤其是对数据库的连接和关闭,几乎都是通用的,所以我们可以将他写成一个工具类

    public class JDBCUtils {
        //创建连接
        public static Connection getConnection() throws Exception {
            //1.获取配置文件
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
            //2.读取配置文件信息
            Properties properties = new Properties();
            properties.load(is);
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String url = properties.getProperty("url");
            String driverClass = properties.getProperty("driverClass");
            //3.注册驱动,连接数据库
            Class.forName(driverClass);
            Connection connection = DriverManager.getConnection(url, user, password);
            return connection;
        }
    	//关闭连接
        public static void closeConnection(Connection connection, Statement ps)  {
            try {
                if(ps != null) {
                    ps.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    

    现在我们使用工具类来实现对数据的更新操作

    1. 创建连接
    2. 预编译sql
    3. 填充占位符
    4. 执行sql
    5. 关闭连接
    @Test
        public void UpdateTest(){
            Connection conn = null;
            PreparedStatement ps = null;
            try {
                //1.创建连接
                conn = JDBCUtils.getConnection();
                //2.预编译sql,返回一个preparedStatement的实例
                String sql = "update customers set name = ? , email = ? where id = ?";
                ps = conn.prepareStatement(sql);
                //3.填充占位符
                ps.setObject(1,"老子");
                ps.setObject(2,"laozi@666.com");
                ps.setObject(3,22);
                //4.执行sql
                ps.execute();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //5.关闭连接
                JDBCUtils.closeConnection(conn,ps);
            }
        }
    
  • 删除数据

    经过以上的两个方法,我们可以看出增删改只有预编译sql和填充占位符不一样,那我们可以将sql语句和占位符通过参数传进去,我们写一个通用的方法来实现增删改操作

    //因为占位符数量是不确定的,我们通过可变形参来传入,并且可变形参的长度要跟占位符的数量相同
    public void update(String sql,Object ...args){
            Connection conn = null;
            PreparedStatement ps = null;
            try {
                //1.创建链接
                conn = JDBCUtils.getConnection();
                //2.预编译sql,返回一个preparedStatement的实例
                ps = conn.prepareStatement(sql);
                //3.填充占位符
                for (int i = 0; i < args.length; i++) {
                    //注意:数据库的下标是从1开始的,而Java中数组、集合等下标是从0开始
                    ps.setObject(i+1,args[i]);
                }
                //4.执行sql
                ps.execute();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //5.关闭连接
                JDBCUtils.closeConnection(conn,ps);
            }
    }
    //删除操作
    @Test
    public void test(){
        String sql = "delete from customers where id = ?";
        update(sql,23);
    }
    

增删改看完之后,我们重点来看一下与众不同的查询操作

  1. 建立连接
  2. 预编译sql
  3. 填充占位符
  4. 执行sql语句并返回数据
    • 调用executeQuery()方法,返回一个resultSet的实例
    • resultSet有一个next方法,类似于集合的迭代器,这里next方法是查看下面是否还有数据,有的话指针下移,没有的话结束
  5. 关闭连接
@Test
    public void test1() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            //1.建立连接
            conn = JDBCUtils.getConnection();
            //2.预编译sql
            String sql = "select id,name,email,birth from customers where id = ?";
            ps = conn.prepareStatement(sql);
            //3.填充占位符
            ps.setObject(1,1);
            //4.执行sql语句并返回数据
            resultSet resultSet = ps.executeQuery();
            if(resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String email = resultSet.getString(3);
                Date brith = resultSet.getDate(4);
                /*
                一般我们采取ORM编程思想
                一个数据表对应一个Java类,表中一条记录对应一个对象,表中的字段对应对象的属性
                 */
                //创建一个customers类来接受数据
                Customers customers = new Customers(id, name, email, brith);
                System.out.println(customers);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //5.关闭连接
            JDBCUtils.closeConnection(conn,ps,resultSet);
        }
    }

接着我们希望可以写一个对customers表执行查询操作的工具类,因为每次需要显示的字段不同,条件不同,上述方法执行起来代码量有点大

与增删改的工具类一样的是,需要传的参数还是一条sql语句跟相对于的占位符数据,不同的是我们需要返回一个查询到的结果集

我们来举例说一下思路,我们需要查询下面这条sql语句

select id,name,email from customers where id  = ?

我们每次需要查询的列名的数量是不同的,所以我们在创建Customers对象时,就无法通过构造器的方法创建,那我们的解决方法是

通过空参构造器创建,再通过反射机制设置运行时类的属性

	 public ArrayList<Customers> queryCustomers(String sql, Object ...args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<Customers> customersArray = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1,args[i]);
            }
            rs = ps.executeQuery();
            //获取表的元数据
            ResultSetMetaData metaData = rs.getMetaData();
            //获取列的数量
            int columnCount = metaData.getColumnCount();
            customersArray = new ArrayList<>();
            while (rs.next()){
                Customers customers = new Customers();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = rs.getObject(i + 1);
                    //获取列的列名
                    String columnName = metaData.getColumnName(i + 1);
                    //数据库的字段名和customers的属性名是一一对应的,需要使用反射机制,动态的调用set方法
                    Field field = Customers.class.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(customers,columnValue);
                }
                customersArray.add(customers);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeConnection(conn,ps,rs);
        }
        return customersArray;
    }

	//调用以上方法
	@Test
    public void queryCustomersTest() throws Exception {
        String sql = "select id,name,email from customers";
        ArrayList<Customers> customers = queryCustomers(sql);
        for (Customers c: customers) {
            System.out.println(c);
        }
    }

上述方法中有一个非常关键的信息:字段名需要和我们创建的对象属性名完全一样。而在实际开发过程中,经常会出现两者不一样的情景,那我们该如何操作呢?

  1. 我们在声明sql时,使用类的属性名来命名字段的别名

    select 字段1 别名1,字段2 别名2 from
  2. 使用ResultSetMetaData,需要将getColumnName()替换成getColumnLabel()来获取字段的别名

  3. 如果字段没有别名时,getColumnLabel会直接获取字段的列名

所以我们可以将上面的工具类修改一下

public ArrayList<Customers> queryCustomers(String sql, Object ...args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<Customers> customersArray = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1,args[i]);
            }
            rs = ps.executeQuery();
            //我们需要列的信息
            ResultSetMetaData metaData = rs.getMetaData();
            //获取列的数量
            int columnCount = metaData.getColumnCount();
            customersArray = new ArrayList<>();
            while (rs.next()){
                Customers customers = new Customers();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = rs.getObject(i + 1);

                    //获取列的列名
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    //数据库的字段名和customers的属性名是一一对应的,需要使用反射机制,动态的调用set方法
                    Field field = Customers.class.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(customers,columnValue);
                }
                customersArray.add(customers);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeConnection(conn,ps,rs);
        }
        return customersArray;
    }

我们在实际开发过程中,发现查询的不单单是这一张表,那么生性懒惰的人类总会发明新的方法,那我们现在就来写一下所有表的通用方法的工具类

核心思想:对于不明确的类,我们需要在调用的时候传入一个类的参数,然后通过反射机制,动态的创建对象

	//工具类
	public <T> ArrayList<T> queryCurrenArray(Class<T> clazz, String sql, Object ...args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1,args[i]);
            }
            resultSet = ps.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            ArrayList<T> arrayList = new ArrayList<>();
            while (resultSet.next()){
                //创建一个传入class类的对象
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    Object object = resultSet.getObject(i + 1);
                    String columnLabel = metaData.getColumnLabel(i + 1);

                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,object);
                }
                arrayList.add(t);
            }
            return  arrayList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(conn != null) {
                    conn.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                if(ps != null) {
                    ps.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                if(resultSet != null) {
                    resultSet.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return null;
        }
    }

	//测试方法
	@Test
    public void test2() throws Exception {
        String sql = "select id,name from customers";
        ArrayList<Customers> customers = queryCurrenArray(Customers.class, sql);
        if(customers.size() > 0) {
            customers.forEach(System.out::println);
        }else {
            System.out.println("无此数据");
        }
    }

总结

  • 增删改中PreparedStatement.execute()返回值为boolean类型,如果返回true的话,代表执行的是DQL语句,如果返回值为false,代表执行的DML语句。那么可以得出结论,如果开发过程中DML语句需要返回值,这个方式不适用。

    实际上我们可以调用PreparedStatement.executeUpdate(),此方法返回值为int类型,如果返回值不为0,则代表数据库有几条数据进行了修改,如果返回值为0,则代表数据库中没有数据被修改,即修改失败

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值