JDBC封装

1.前言

原生的JDBC的操作其实是比较繁琐的,而且其中有很多的重复性代码,这个时候,我们可以考虑自己对JDBC进行一个简单的封装,封装成自己想要的,比较方便的小工具。

2.封装JDBC

为了使得编辑参数更加方便,首先将数据库连接参数抽取出来放在配置文件jdcb.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/singerdb?useUnicode=true&characterEncoding=UTF-8
jdbc.user=root
jdbc.password=123456

然后在类加载的时候加载该配置文件,并且注册驱动类信息

private static Properties properties;

static {
    properties = new Properties();
    try {
        properties.load(new FileInputStream("config/jdbc.properties"));
        System.out.println("load config file finish");
        Class.forName(properties.getProperty("jdbc.driver"));
    } catch (FileNotFoundException e) {
        System.out.println("jdbc config file not found " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        System.out.println("jdbc class not found " + e.getMessage());
    }
}

接着封装获取连接对象getConnection()

/**
  * 01-获得数据库连接Connection
  * @return Connection 数据库连接
  */
 private static Connection getConnection() {
     Connection connection = null;
     try {
         connection = DriverManager.getConnection(
                 properties.getProperty("jdbc.url"),
                 properties.getProperty("jdbc.user"),
                 properties.getProperty("jdbc.password"));
     } catch (SQLException e) {
         System.out.println("cannot get connection " + e.getMessage());
     }
     return connection;
 }

然后封装关闭各种资源的方法close()

  /**
    * 关闭connection
    * @param connection 连接池对象
    */
   private static void close(Connection connection) {
       if (connection != null) {
           try {
               connection.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
   }

   /**
    * 关闭Statement
    * @param statement
    */
   private static void close(Statement statement) {
       if (statement != null) {
           try {
               statement.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
   }

   /**
    * 关闭ResultSet
    *
    * @param resultSet
    */
   private static void close(ResultSet resultSet) {
       if (resultSet != null) {
           try {
               resultSet.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
   }

   /**
    * 关闭Connection 以及Statement
    * @param connection
    * @param statement
    */
private static void close(Connection connection, Statement statement) {
       close(connection);
       close(statement);
}

   /**
    * 关闭Connection,Statement以及ResultSet
    * @param connection
    * @param statement
    * @param resultSet
    */
private static void close(Connection connection, Statement statement, ResultSet resultSet) {
       close(connection, statement);
       close(resultSet);
}

接着封装更新方法,正如所知道的,更新包括插入、删除、修改,所以可以将这些操作封装在一个方法即可

    /**
     * 03-更新操作
     * @param sql   执行的SQL语句
     * @param param 对应的参数列表
     * @return
     */
    public static boolean update(String sql, Object... param) {
        PreparedStatement preparedStatement = null;
        Connection connection = getConnection();
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (settingParams(preparedStatement, param) == false) {
                return false;
            }
            int result = preparedStatement.executeUpdate();
            if (result > 0) {
                return true;
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(connection, preparedStatement);
        }
        return false;
    }

上面封装了一个方法settingParams(),作用是利用元数据信息,根据SQL语句中的占位符个数,将对应的参数注入进去

/**
     * 02-设置参数
     * @param preparedStatement Statement对象
     * @param param             参数列表
     * @return
     * @throws SQLException
     */
private static boolean settingParams(PreparedStatement preparedStatement, Object... param) throws SQLException {
        if (param != null && param.length > 0) {
            ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
            int paramCount = parameterMetaData.getParameterCount();
            if (paramCount != param.length) {
                return false;
            }
            for (int i = 0; i < paramCount; i++) {
                preparedStatement.setObject(i + 1, param[i]);
            }
        }
        return true;
}

由于查询返回的类型非常多,这里只是封装两个常用的方法,一个是queryForBean()返回单个对象,一个是queryForList()返回List,这里需要注意的是,由于只是简单的封装,所以没有做对象属性名与数据表列名的映射,所以需要保证属性名与列名相同,为了更加方便进行操作,使用了泛型机制,并且使用了反射技术进行属性的注入操作

     /**
     * 获取单个Bean
     *
     * @param sql   执行SQL语句
     * @param param 对应的参数列表
     * @param clazz 所要获取的对象的类型
     * @param    对象的类型
     * @return bean
     */
    public static <T> T queryForBean(String sql, Class<T> clazz, Object... param) {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (settingParams(preparedStatement, param) == false) {
                return null;
            }
            resultSet = preparedStatement.executeQuery();
            if (resultSet == null) {
                return null;
            }
            if (resultSet.next()) {
                T data = clazz.newInstance();
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                int columnCount = resultSetMetaData.getColumnCount();
                for (int i = 0; i < columnCount; i++) {
                    String name = resultSetMetaData.getColumnName(i + 1);
                    Object rData = resultSet.getObject(name);
                    //System.out.println(name+"---"+rData);
                    JDBCUtils.bulidBean(data, name, rData);
                }
                //System.out.println(data);
                return data;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(connection, preparedStatement, resultSet);
        }
        return null;
    }

    /**
     * 获取Bean并且封装成List
     *
     * @param sql   执行SQL语句
     * @param param 对应的参数列表
     * @param clazz 所要获取的对象的类型
     * @param    对象的类型
     * @return list
     */
    public static <T> List<T> queryForList(String sql, Class<T> clazz,Object... param) {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (settingParams(preparedStatement, param) == false) {
                return null;
            }
            resultSet = preparedStatement.executeQuery();
            if (resultSet == null) {
                return null;
            }
            List<T> results = new ArrayList<>();
            while (resultSet.next()) {
                T data = clazz.newInstance();
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                int columnCount = resultSetMetaData.getColumnCount();
                for (int i = 0; i < columnCount; i++) {
                    String name = resultSetMetaData.getColumnName(i + 1);
                    Object rData = resultSet.getObject(name);
                    JDBCUtils.bulidBean(data, name, rData);
                }
                results.add(data);
            }
            return results;
        }  catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(connection, preparedStatement, resultSet);
        }
        return null;
    }

    private static Object bulidBean(Object bean, String name, Object value){
        try {
            Class c = bean.getClass();
            String firstChar = String.valueOf(name.charAt(0)).toUpperCase();
            String meThodName="set"+firstChar+name.substring(1);
            Field declaredField = c.getDeclaredField(name);
            Class type = declaredField.getType();
            Method declaredMethod = c.getDeclaredMethod(meThodName, type);
            //System.out.println(meThodName+"---"+declaredField+"----"+type.getName()+"----"+value);
            if(value instanceof Date){
                value=String.valueOf(value);
            }
            declaredMethod.invoke(bean,value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return bean;
    }

至此,通过简单的封装,一个简单的JDBC操作工具就封装好了,这样,当需要的时候就可以非常方便地使用了,而且,当需要其他返回类型的时候,基本上只要按照上面的思路进行处理即可。

完整的代码如下所示:


package com.bruce.utils;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


public class JDBCUtils {

    private static Properties properties;

    static {
        properties = new Properties();
        try {
            properties.load(new FileInputStream("config/jdbc.properties"));
            System.out.println("load config file finish");
            Class.forName(properties.getProperty("jdbc.driver"));
        } catch (FileNotFoundException e) {
            System.out.println("jdbc config file not found " + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            System.out.println("jdbc class not found " + e.getMessage());
        }
    }

    /**
     * 01-获得数据库连接Connection
     * @return Connection 数据库连接
     */
    private static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(
                    properties.getProperty("jdbc.url"),
                    properties.getProperty("jdbc.user"),
                    properties.getProperty("jdbc.password"));
        } catch (SQLException e) {
            System.out.println("cannot get connection " + e.getMessage());
        }
        return connection;
    }


    /**
     * 02-设置参数
     * @param preparedStatement Statement对象
     * @param param             参数列表
     * @return
     * @throws SQLException
     */
    private static boolean settingParams(PreparedStatement preparedStatement, Object... param) throws SQLException {
        if (param != null && param.length > 0) {
            ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
            int paramCount = parameterMetaData.getParameterCount();
            if (paramCount != param.length) {
                return false;
            }
            for (int i = 0; i < paramCount; i++) {
                preparedStatement.setObject(i + 1, param[i]);
            }
        }
        return true;
    }


    /**
     * 03-更新操作
     * @param sql   执行的SQL语句
     * @param param 对应的参数列表
     * @return
     */
    public static boolean update(String sql, Object... param) {
        PreparedStatement preparedStatement = null;
        Connection connection = getConnection();
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (settingParams(preparedStatement, param) == false) {
                return false;
            }
            int result = preparedStatement.executeUpdate();
            if (result > 0) {
                return true;
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(connection, preparedStatement);
        }
        return false;
    }

    /**
     * 获取单个Bean
     *
     * @param sql   执行SQL语句
     * @param param 对应的参数列表
     * @param clazz 所要获取的对象的类型
     * @param    对象的类型
     * @return bean
     */
    public static <T> T queryForBean(String sql, Class<T> clazz, Object... param) {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (settingParams(preparedStatement, param) == false) {
                return null;
            }
            resultSet = preparedStatement.executeQuery();
            if (resultSet == null) {
                return null;
            }
            if (resultSet.next()) {
                T data = clazz.newInstance();
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                int columnCount = resultSetMetaData.getColumnCount();
                for (int i = 0; i < columnCount; i++) {
                    String name = resultSetMetaData.getColumnName(i + 1);
                    Object rData = resultSet.getObject(name);
                    //System.out.println(name+"---"+rData);
                    JDBCUtils.bulidBean(data, name, rData);
                }
                //System.out.println(data);
                return data;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(connection, preparedStatement, resultSet);
        }
        return null;
    }

    /**
     * 获取Bean并且封装成List
     *
     * @param sql   执行SQL语句
     * @param param 对应的参数列表
     * @param clazz 所要获取的对象的类型
     * @param    对象的类型
     * @return list
     */
    public static <T> List<T> queryForList(String sql, Class<T> clazz,Object... param) {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (settingParams(preparedStatement, param) == false) {
                return null;
            }
            resultSet = preparedStatement.executeQuery();
            if (resultSet == null) {
                return null;
            }
            List<T> results = new ArrayList<>();
            while (resultSet.next()) {
                T data = clazz.newInstance();
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                int columnCount = resultSetMetaData.getColumnCount();
                for (int i = 0; i < columnCount; i++) {
                    String name = resultSetMetaData.getColumnName(i + 1);
                    Object rData = resultSet.getObject(name);
                    JDBCUtils.bulidBean(data, name, rData);
                }
                results.add(data);
            }
            return results;
        }  catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(connection, preparedStatement, resultSet);
        }
        return null;
    }

    /**
     * 关闭connection
     * @param connection 连接池对象
     */
    private static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭Statement
     * @param statement
     */
    private static void close(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭ResultSet
     *
     * @param resultSet
     */
    private static void close(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭Connection 以及Statement
     * @param connection
     * @param statement
     */
    private static void close(Connection connection, Statement statement) {
        close(connection);
        close(statement);
    }

    /**
     * 关闭Connection,Statement以及ResultSet
     * @param connection
     * @param statement
     * @param resultSet
     */
    private static void close(Connection connection, Statement statement, ResultSet resultSet) {
        close(connection, statement);
        close(resultSet);
    }

    private static Object bulidBean(Object bean, String name, Object value){
        try {
            Class c = bean.getClass();
            String firstChar = String.valueOf(name.charAt(0)).toUpperCase();
            String meThodName="set"+firstChar+name.substring(1);
            Field declaredField = c.getDeclaredField(name);
            Class type = declaredField.getType();
            Method declaredMethod = c.getDeclaredMethod(meThodName, type);
            //System.out.println(meThodName+"---"+declaredField+"----"+type.getName()+"----"+value);
            if(value instanceof Date){
                value=String.valueOf(value);
            }
            declaredMethod.invoke(bean,value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return bean;
    }
}

你可能感兴趣的:(JDBC专题)