package ink.wgink.util.jdbc;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.*;

/**
 * @ClassName: JdbcUtil
 * @Description: Jdbc
 * @Author: WangGeng
 * @Date: 2019-07-14 18:53
 * @Version: 1.0
 **/
public class JdbcUtil {

    /**
     * 获取单条信息
     *
     * @param resultSet
     * @return
     */
    public static Map<String, Object> getResult(ResultSet resultSet) {
        List<Map<String, Object>> resultList = listResult(resultSet);
        if (resultList.isEmpty()) {
            return null;
        }
        return resultList.get(0);
    }

    /**
     * 查询列表
     *
     * @param resultSet
     * @return
     */
    public static List<Map<String, Object>> listResult(ResultSet resultSet) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        try {
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int columnCount = resultSetMetaData.getColumnCount();
            while (resultSet.next()) {
                Map<String, Object> row = new LinkedHashMap<>(16);
                for (int i = 0; i < columnCount; i++) {
                    row.put(resultSetMetaData.getColumnLabel(i + 1), resultSet.getObject(i + 1));
                }
                resultList.add(row);
            }
        } catch (Exception e) {
            return new ArrayList<>();
        }
        return resultList;
    }

}
