JdbcUtil

文章目录


#JDBC封装

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jdbc.DatabaseDriver;

import java.sql.*;
import java.util.*;

@Slf4j
public class JdbcUtil {

    public static String DRIVER_SQLITE = "org.sqlite.JDBC";
    public static String SQLITE_URL_PREFIX = "jdbc:sqlite:";
    public static String DRIVER_MYSQL = "com.mysql.cj.jdbc.Driver";
    public static String MYSQL_URL_PREFIX = "jdbc:mysql://";

    // 定义数据库连接
    private volatile static Connection sqliteConnection;
    private volatile static Connection mysqlConnection;
    // 定义sql语句的执行对象
    private volatile static PreparedStatement sqlitePstmt;
    private volatile static PreparedStatement mysqlPstmt;
    // 定义查询返回的结果集合
    private volatile static ResultSet sqliteResultSet;
    private volatile static ResultSet mysqlResultSet;

//    static {
//        loadConfig();
//    }

    /**
     * 加载数据库配置信息
     */
//    public static void loadConfig() {
//
//        try {
//            InputStream inStream = JdbcUtil.class.getResourceAsStream("classpath:jdbc.properties");
//            Properties prop = new Properties();
//            prop.load(inStream);
//            USERNAME = prop.getProperty("jdbc.username");
//            PASSWORD = prop.getProperty("jdbc.password");
//            DRIVER = prop.getProperty("jdbc.driver");
//            URL = prop.getProperty("jdbc.url");
//        } catch (IOException e) {
//            throw new RuntimeException("读取数据库配置文件异常!", e);
//        }
//    }

//    public JdbcUtil() {
//        super();
//    }

    /**
     * 获取数据库连接
     *
     * @return
     */

    public static Connection getMysqlConnection(String ip, String name, String userName, String password) throws SQLException, ClassNotFoundException {
        Class.forName(DatabaseDriver.MYSQL.getDriverClassName());
        mysqlConnection = DriverManager.getConnection(JdbcUtil.MYSQL_URL_PREFIX+ip+":3306/"+name+"?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&connectTimeout=500&socketTimeout=60000", userName, password);
        return mysqlConnection;
    }
    public static Connection getSqliteConnection(String driver, String url) throws SQLException, ClassNotFoundException {
        Class.forName(driver);
        sqliteConnection = DriverManager.getConnection(url);
        return sqliteConnection;
    }

    /**
     * 执行更新操作
     *
     * @param sql    sql语句
     * @param params 执行参数
     * @return 执行结果
     * @throws SQLException
     */
//    public boolean updateByPreparedStatement(String sql, List<?> params)
//            throws SQLException {
//        boolean flag = false;
//        int result = -1;
//        sqlitePstmt = sqliteConnection.prepareStatement(sql);
//        int index = -1;
//        // 填充sql语句中的占位符
//        if (params != null && !params.isEmpty()) {
//            for (int i = 0; i < params.size(); i++) {
//                sqlitePstmt.setObject(index++, params.get(i));
//            }
//        }
//        result = sqlitePstmt.executeUpdate();
//        flag = result > 0 ? true : false;
//        return flag;
//    }

    /**
     * 执行查询操作
     *
     * @param sql    sql语句
     * @param params 执行参数
     * @return
     * @throws Exception
     */
    public static <T> List<T> sqliteFindResult(String sql, List<?> params, Class<T> cls) throws Exception {
        List<T> listItem = new ArrayList<T>();
        int index = 1;
        try {
            sqlitePstmt = sqliteConnection.prepareStatement(sql);
        }catch (Exception e){
            throw new Exception();
        }
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                sqlitePstmt.setObject(index++, params.get(i));
            }
        }
        sqliteResultSet = sqlitePstmt.executeQuery();
        ResultSetMetaData metaData = sqliteResultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (sqliteResultSet.next()) {
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = sqliteResultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
            listItem.add(MapUtil.parseMap2Object(map, cls));
        }
        return listItem;
    }

    public static <T> List<T> mysqlFindResult(String sql, List<?> params, Class<T> cls) throws Exception {
        List<T> listItem = new ArrayList<T>();
        int index = 1;
        try {
            mysqlPstmt = mysqlConnection.prepareStatement(sql);
        }catch (Exception e){
            throw new Exception();
        }
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                mysqlPstmt.setObject(index++, params.get(i));
            }
        }
        mysqlResultSet = mysqlPstmt.executeQuery();
        ResultSetMetaData metaData = mysqlResultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (mysqlResultSet.next()) {
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = mysqlResultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
            listItem.add(MapUtil.parseMap2Object(map, cls));
        }
        return listItem;
    }

    /**
     * 释放资源
     */
    public synchronized void releaseConn(ResultSet resultSet, PreparedStatement pstmt, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Map;

@Slf4j
public class MapUtil {
    public static Object convert2Object(Class clazz, Map<String, Object[]> map) throws
            IntrospectionException, InstantiationException, IllegalAccessException {

        BeanInfo bi = Introspector.getBeanInfo(clazz);

        Object obj = clazz.newInstance();

        PropertyDescriptor[] pds = bi.getPropertyDescriptors();

        String pName;
        for (PropertyDescriptor pd : pds) {
            pName = pd.getName();
            if (map.containsKey(pName)) {
                try {
                    pd.getWriteMethod().invoke(obj, map.get(pName)[0]);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

        return obj;
    }

    /**
     * 将Map转换为对象
     *
     * @param paramMap
     * @param cls
     * @return
     */
    public static <T> T parseMap2Object(Map<String, Object> paramMap, Class<T> cls) {
        return JSONObject.parseObject(JSONObject.toJSONString(paramMap), cls);
    }
}

    <!--                       map转对象         -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.46.sec01</version>
        </dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值