package com.example.repurchase.utils;

import com.alibaba.fastjson.JSONObject;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SqlUtils {

    public static List<JSONObject> convertSqlRresultToJson(ResultSet resultSet) throws SQLException {
        ResultSetMetaData rsmd = resultSet.getMetaData();
        List<JSONObject> list = new ArrayList();
        while (resultSet.next()) {
            JSONObject jsonObject = new JSONObject();
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                jsonObject.put(rsmd.getColumnName(i), resultSet.getString(rsmd.getColumnName(i)));
            }
            list.add(jsonObject);
        }
        resultSet.close();
        return list;
    }

    public static List<HashMap<String, Object>> convertSqlRresultToHashMap(ResultSet resultSet) throws SQLException {
        ResultSetMetaData rsmd = resultSet.getMetaData();
        List<HashMap<String, Object>> list = new ArrayList();
        while (resultSet.next()) {
            HashMap<String, Object> hashMap = new HashMap<String, Object>();
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                hashMap.put(rsmd.getColumnName(i), resultSet.getString(rsmd.getColumnName(i)));
            }
            list.add(hashMap);
        }
        resultSet.close();
        return list;
    }
    /**
     * 获取连接
     * @param dataSource
     * @return
     * @throws SQLException
     */
    public static Connection getConnection(DataSource dataSource) throws SQLException {
        return dataSource.getConnection();
    }


    /**
     * 关闭连接或者传输器
     * @param connection
     * @param statement
     * @throws SQLException
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {

        if(resultSet != null){
            resultSet.close();
        }

        if(statement != null){
            statement.close();
        }

        if(connection != null){
            connection.close();
        }
    }

}
