JDBC--连接工具类实现

2019-03-05  本文已影响0人  年少懵懂丶流年梦

jdbc.properties

jdbc.username=root
jdbc.password=111111
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/student
public class JdbcUtil {
    
    private static String USERNAME;
    private static String PASSWORD;
    private static String DRIVER;
    private static String URL;
    
    // 定义数据库连接
    private Connection connection;
    // 定义sql语句的执行对象
    private PreparedStatement pstmt;
    // 定义查询返回的结果集合
    private ResultSet resultSet;
    
    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 Connection getConnection() {
        try {
            Class.forName(DRIVER);
            DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception e) {
            throw new RuntimeException("获取Connection出现异常!", e);
        }
        return connection;
    }
    
    /**
     * 执行更新操作
     * @param sql sql语句
     * @param params 执行参数
     * @return 执行结果
     * @throws SQLException
     */
    public boolean updateByPreparedStatement(String sql, List<?> params) 
        throws SQLException {
        boolean flag = false;
        int result = -1;
        pstmt = connection.prepareStatement(sql);
        int index = -1;
        // 填充sql语句中的占位符
        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;
    }
    
    /**
     * 执行查询操作
     * @param sql sql语句
     * @param params 执行参数
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> findResult(String sql, List<?> params) 
            throws Exception {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        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 cols_len = metaData.getColumnCount();
        while(resultSet.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 = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
            list.add(map);
        }
        return list;
    }
    
    /**
     * 释放资源
     */
    public void releaseConn() {
        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();
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读