java-CRUD封装

来源:互联网 发布:淘宝客服规范 编辑:程序博客网 时间:2024/06/05 16:02

java-CRUD封装

对获取连接进行封装

package mysql;

    public static Connection getConnection() {        final  String url = "jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&useUTF-8=true&character=utf-8&useSSL=true";        final  String user = "root";        final  String password = "xxxx";        Connection connection=null;        try {            Class.forName("com.mysql.jdbc.Driver");            connection = DriverManager.getConnection(url, user, password);        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (SQLException e) {            e.printStackTrace();        }        return connection;    }

对关闭连接进行封装

public static void closeAll(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){        try {            if (connection!=null){                connection.close();            }            if (preparedStatement!=null){                preparedStatement.close();            }            if (resultSet!=null){                preparedStatement.close();            }        } catch (SQLException e) {            e.printStackTrace();        }    }

对增删改进行封装

 public static int ExecuteUpdate(String sql, Object ...s){        int result=0;        Connection connection=null;        PreparedStatement preparedStatement=null;        try {             connection=getConnection();             preparedStatement = connection.prepareStatement(sql);            for (int i = 0; i < s.length; i++) {                preparedStatement.setObject(i+1,s[i]);            }            result = preparedStatement.executeUpdate();        } catch (SQLException e) {            e.printStackTrace();        }finally {            closeAll(connection,preparedStatement,null);        }        return result;    }

对查询进行封装

    public static <T> List ExcuteQuery(String sql , QueryMap<T> queryMap){        List<T> list=new ArrayList<>();        Connection connection=getConnection();        PreparedStatement preparedStatement=null;        ResultSet resultSet=null;        try {             preparedStatement = connection.prepareStatement(sql);             resultSet=preparedStatement.executeQuery();             while (resultSet.next()){                list.add(queryMap.MapSet(resultSet)) ;             }        } catch (SQLException e) {            e.printStackTrace();        }finally {            closeAll(connection,preparedStatement,resultSet);        }        return list;    }public interface QueryMap<T> {    <T> T MapSet(ResultSet resultSet);}

注意:在对查询进行封装时,其对ResultSet中信息取出还是在Dao中实现的,用匿名内部类实现,在这里使用泛型,思路更清晰,代码更简练。

总结

1.对于SQLUtil工具类其中的方法都应该是static的,因为方便使用不需要new
2.在对其打开和关闭进行封装,注意关闭的通用性
3.对增删改进行封装,注意多个参数…的使用,其本质是数组。
4.对于prepareset中的setObject使用和Object更深的理解。
5.在查询时可以使用反射和接口进行封装,通过接口在不同情况下的不同实现进行封装。

最后展示

这里写图片描述

增删改查几行代码搞定

在增删改查中事务使用con.setAutoCommit(false);
在提交时con.commit();

原创粉丝点击