• JDBC 5—— 查的操作


    Java与SQL对应数据类型转换表

    Java类型 SQL类型
    boolean BIT
    byte TINYINT
    short SMALLINT
    int INTEGER
    long BIGINT
    String CHAR,VARCHAR,LONGVARCHAR
    byte array BIGARY,VAR BINARY
    java.sql.Date DATE
    java.sql.Time TIME
    java.sql.Timestamp TIMESTAMP

     重载关闭资源的操作

        /*
         * 关闭资源的操作
         */
        public static void closeResource(Connection conn, PreparedStatement ps, ResultSet rs) {
            try {
                if (ps != null)
                    ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    先从特殊的一个表的一个查询开始,然后在将一个表的查询扩展到一个通用的语句,以下是针对于Customers表的查询操作,其中便包含了这两项。

    package com.JDBCStudy3.PreparedStatement.crud;
    
    import java.sql.Connection;
    import java.sql.Date;
    import java.sql.PreparedStatement;
    
    import com.mysql.jdbc.ResultSet;
    import com.mysql.jdbc.ResultSetMetaData;
    
    import JDBC_util.JDBCutils;
    
    /*
     * 针对于Customers表的查询操作
     * */
    public class CustomerForQuery {
        public void testQueryForCustmers() {
            String sql = "select id,name,birth,email from customers where id = ?";
            Customer customer = queryForCustomers(sql,13);
            System.out.println(customer);
            
            sql = "select name,email from customers where name = ?";
            customer = queryForCustomers(sql,"周杰伦");
            System.out.println(customer);
        }
        
        
        /*
         * 针对customers表的通用的查询操作
         */
        public Customer queryForCustomers(String sql, Object... args) {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                conn = JDBCutils.getConnection();
                ps = conn.prepareStatement(sql);
                for (int i = 0; i < args.length; i++) {
                    ps.setObject(i + 1, args[i]);
                }
    
                rs = (ResultSet) ps.executeQuery();
                // 获取结果集的元数据ResultSetMetaData String name = "TOM";
                ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
                // 通过ResultSetMetaData获取结果集中的列数
                int columnCount = rsmd.getColumnCount();
                if (rs.next()) {
                    Customer cust = new Customer();
                    // 处理结果集一行数据中的每一个列
                    for (int i = 0; i < columnCount; i++) {
                        // 获取列值
                        Object columnValue = rs.getObject(i + 1);
    
                        // 获取每个列的列名
                        String columnName = rsmd.getColumnName(i + 1);
    
                        // 给cust对象指定的某个属性,赋值为columnValue,通过反射
                        java.lang.reflect.Field field = Customer.class.getDeclaredField(columnName);
                        field.setAccessible(true);
                        field.set(cust, columnValue);
                    }
                    return cust;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCutils.closeResource(conn, ps, rs);
            }
            return null;
        }
    
        
        public void testQuery1() {
            Connection conn = null;
            PreparedStatement ps = null;
            // 执行,并返回结果集
            ResultSet resultSet = null;
            try {
                conn = JDBCutils.getConnection();
                String sql = "select id,name,email,birth from customers where id = ?";
                ps = conn.prepareStatement(sql);
    
                resultSet = (ResultSet) ps.executeQuery();
                // 处理结果集
                if (resultSet.next()) {
                    // 判断结果集的下一条是否有数据,如果有数据返回true,并指针下移,如果返回false,指针不下移,结束
                    // 获取当前这条数据的各个字段值
                    int id = resultSet.getInt(1);
                    String name = resultSet.getString(2);
                    String email = resultSet.getString(3);
                    Date birth = resultSet.getDate(4);
    
                    // 方式一:
                    System.out.println("id = " + id + ",name = " + name + ",email = " + email + " birth = " + birth);
                    // 方式二:
                    Object[] data = new Object[] { id, name, email, birth };
                    // 方式三:将数据封装成一个对象(推荐)
                    Customer customer = new Customer(id, name, email, birth);
                    System.out.println(customer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭资源操作
                JDBCutils.closeResource(conn, ps, resultSet);
            }
        }
    }

     customer类

    package com.JDBCStudy3.PreparedStatement.crud;
    
    import java.sql.Date;
    
    /*
     * ORM编程思想(object relational mapping)
     * 一个数据表对应一个java类
     * 表中的一个记录对应Java类的一个对象
     * 表中的一个字段对应Java类的一个属性
     * */
    public class Customer {
        private int id;
        private String name;
        private String email;
        private Date birth;
    
        public Customer(int id, String name, String email, Date birth) {
            super();
            this.id = id;
            this.name = name;
            this.email = email;
            this.birth = birth;
        }
    
        public Customer() {
            super();
        }
    
        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 String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public Date getBirth() {
            return birth;
        }
    
        public void setBirth(Date birth) {
            this.birth = birth;
        }
    
        @Override
        public String toString() {
            return "Customer [id=" + id + ", name=" + name + ", email=" + email + ", birth=" + birth + "]";
        }
    }

    有了customer表的查找操作,在试试order表的查询

    下图为编程的思想图

    package com.JDBCStudy3.PreparedStatement.crud;
    
    import java.lang.reflect.Field;
    import java.sql.Connection;
    import java.sql.Date;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    
    import org.junit.Test;
    
    import JDBC_util.JDBCutils;
    
    /*
     * 针对于Order表的通用的查询操作
     * */
    public class OrderForQuery {
        /*
         * 针对于表的字段名与类的属性名不相同的情况:
         * 1、必须声明sql时,使用类的属性名来命名字段的别名
         * 2、使用ResultSetMetaData时,需要使用getColumnLabel()来替换getColumnName(),获取列的别名
         * 说明:如果sql中没有给字段取别名,getColumnLabel()获取的就是列名
         * */
        
        @Test
        public void testOrederForQuery() {
            String sql = "select order_id orderId,order_name orderName,order_date orderDate from `order` where order_id = ?";
            Order order = orderForQuery(sql, 1);
            System.out.println(order);
        }
    
        /*
         * 通用的针对于Order表的查询操作
         */
        @SuppressWarnings("finally")
        public Order orderForQuery(String sql, Object... args) {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = 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 rsmd = rs.getMetaData();
                // 获取列数
                int columnCount = rsmd.getColumnCount();
                if (rs.next()) {
                    Order order = new Order();
                    for (int i = 0; i < columnCount; i++) {
                        // 获取每个列的列值:通过ResultSet
                        Object columnValue = rs.getObject(i + 1);
                        /*
                         * 通过ResultSetMetaData
                         * 获取列的列名:getColumnName() -- 不推荐使用
                         * 获取列的别名:getColumnLabel()
                         * */
                        //String columnName = rsmd.getColumnName(i + 1);
                        String columnLabel = rsmd.getColumnLabel(i);
                        // 通过反射,将对象指定名columnName的属性赋值为指定的值columnValue
                        Field field = Order.class.getDeclaredField((String) columnLabel);
                        field.setAccessible(true);
                        field.set(order, columnValue);
                    }
                    return order;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCutils.closeResource(conn, ps, rs);
                return null;
            }
        }
    
        public void testQuery1() {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                conn = JDBCutils.getConnection();
                String sql = "select order_id,order_name,order_date from `order` where order_id = ?";
                ps = conn.prepareStatement(sql);
                ps.setObject(1, 1);
    
                rs = ps.executeQuery();
                if (rs.next()) {
                    int id = (int) rs.getObject(1);
                    String name = (String) rs.getObject(2);
                    Date date = (Date) rs.getObject(3);
    
                    Order order = new Order(id, name, date);
                    System.out.println(order);
    
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCutils.closeResource(conn, ps, rs);
            }
        }
    }

    order类

    package com.JDBCStudy3.PreparedStatement.crud;
    
    import java.sql.Date;
    
    public class Order {
        private int orderId;
        private String orderName;
        private Date orderDate;
    
        public Order() {
            super();
        }
    
        public Order(int orderId, String orderName, Date orderDate) {
            super();
            this.orderId = orderId;
            this.orderName = orderName;
            this.orderDate = orderDate;
        }
    
        public int getOrderId() {
            return orderId;
        }
    
        public void setOrderId(int orderId) {
            this.orderId = orderId;
        }
    
        public String getOrderName() {
            return orderName;
        }
    
        public void setOrderName(String orderName) {
            this.orderName = orderName;
        }
    
        public Date getOrderDate() {
            return orderDate;
        }
    
        public void setOrderDate(Date orderDate) {
            this.orderDate = orderDate;
        }
    
        @Override
        public String toString() {
            return "Order [orderId=" + orderId + ", orderName=" + orderName + ", orderDate=" + orderDate + ", getOrderId()="
                    + getOrderId() + ", getOrderName()=" + getOrderName() + ", getOrderDate()=" + getOrderDate()
                    + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString()
                    + "]";
        }
    }
  • 相关阅读:
    .NetMVC过滤器
    Vue-cli配置
    回顾2019年到今天
    八皇后问题
    约瑟夫环问题
    斐波那契函数列
    提高学习效率的方法
    感受爱阅读笔记
    Android IO流汇总
    Android的AsyncTask
  • 原文地址:https://www.cnblogs.com/stu-jyj3621/p/14310000.html
Copyright © 2020-2023  润新知