栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

写个企业级的JdbcUtils

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

写个企业级的JdbcUtils

package com.grm.util;

import com.grm.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class JdbcUtils {
    
    private static final String USERNAME = "root";
    //数据库密码(本身不能明文写在项目中,此处简化了,先不考虑密码加密的问题)
    private static final String PASSWORD = "root";
    //驱动信息
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    //数据库地址
    private static final String URL = "jdbc:mysql://localhost:3306/mydb";
    private Connection connection;
    private PreparedStatement pstmt;
    private ResultSet resultSet;

    
    public JdbcUtils() {
        try {
            Class.forName(DRIVER);
        } catch (Exception e) {
            throw new BusinessException(500, "获取数据库连接驱动异常!");
        }
    }

    
    public Connection getConnection() {
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            throw new BusinessException(500, "获取数据库连接异常!");
        }
        return connection;
    }


    
    public boolean insertOrUpdateOrDelete(String sql, List params) throws SQLException {
        boolean flag;
        int result = -1;
        pstmt = connection.prepareStatement(sql);
        int index = 1;
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        result = pstmt.executeUpdate();
        flag = result > 0 ? true : false;
        return flag;
    }

    
    public Map querySingle(String sql, List params) throws SQLException {
        Map map = new HashMap<>();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetmetaData metaData = resultSet.getmetaData();
        int colLen = metaData.getColumnCount();
        while (resultSet.next()) {
            for (int i = 0; i < colLen; i++) {
                String colName = metaData.getColumnName(i + 1);
                Object colValue = resultSet.getObject(colName);
                colValue = (colValue == null ? "" : colValue);
                map.put(colName, colValue);
            }
        }
        return map;
    }

    
    public List> queryList(String sql, List params) throws SQLException {
        List> list = new ArrayList<>();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (Object param : params) {
                pstmt.setObject(index++, param);
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetmetaData metaData = resultSet.getmetaData();
        int colLen = metaData.getColumnCount();
        while (resultSet.next()) {
            Map map = new HashMap<>();
            for (int i = 0; i < colLen; i++) {
                String colName = metaData.getColumnName(i + 1);
                Object colValue = resultSet.getObject(colName);
                colValue = (colValue == null ? "" : colValue);
                map.put(colName, colValue);
            }
            list.add(map);
        }

        return list;
    }

    
    public  T querySingle(String sql, List params,
                             Class cls) throws Exception {
        T resultObject = null;
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetmetaData metaData = resultSet.getmetaData();
        int colLen = metaData.getColumnCount();
        while (resultSet.next()) {
            // 通过反射机制创建一个实例
            resultObject = cls.newInstance();
            for (int i = 0; i < colLen; i++) {
                String colName = metaData.getColumnName(i + 1);
                Object colValue = resultSet.getObject(colName);
                colValue = (colValue == null ? "" : colValue);
                Field field = cls.getDeclaredField(colName);
                // 打开javabean的访问权限
                field.setAccessible(true);
                field.set(resultObject, colValue);
            }
        }
        return resultObject;

    }

    
    public  List queryList(String sql, List params,
                                 Class cls) throws Exception {
        List list = new ArrayList();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetmetaData metaData = resultSet.getmetaData();
        int colLen = metaData.getColumnCount();
        while (resultSet.next()) {
            //通过反射机制创建一个实例
            T resultObject = cls.newInstance();
            for (int i = 0; i < colLen; i++) {
                String colName = metaData.getColumnName(i + 1);
                Object colValue = resultSet.getObject(colName);
                colValue = (colValue == null ? "" : colValue);
                Field field = cls.getDeclaredField(colName);
                //打开javabean的访问权限
                field.setAccessible(true);
                field.set(resultObject, colValue);
            }
            list.add(resultObject);
        }
        return list;
    }

    
    public void close() {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new BusinessException(500, "关闭数据库连接异常!");
            }
        }
    }
}
 

其中业务异常类BusinessException

package com.grm.exception;


public class BusinessException extends RuntimeException {
    private int code;
    private String message;

    public BusinessException(int code, String message) {
        this.code = code;
        this.message = message;
    }

    // getter setter
}

Springboot怎么捕获全局BusinessException呢

package com.grm.handler;

import com.grm.common.Result;
import com.grm.exception.BusinessException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.StringJoiner;


@RestControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {
    
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(HttpServletRequest req, Exception e) {
        return Result.failed(500, e.getMessage());
    }

    
    @ExceptionHandler(value = BusinessException.class)
    public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
        return Result.failed(500, e.getMessage());
    }
}

 

 

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号