load ResultSet to map - Java java.sql

Java examples for java.sql:ResultSet

Description

load ResultSet to map

Demo Code


//package com.java2s;
import java.sql.*;
import java.util.*;

public class Main {
    private static List<Map<String, Object>> map(ResultSet rs)
            throws SQLException {
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
        try {// www .  j a v  a2  s. c  om
            if (rs != null) {
                ResultSetMetaData meta = rs.getMetaData(); //informasjon om sql svaret
                int numColumns = meta.getColumnCount(); //antall rader i svar
                while (rs.next()) {
                    Map<String, Object> row = new HashMap<String, Object>(); //lager enkel hashmap for hver rad
                    for (int i = 1; i <= numColumns; ++i) {
                        String name = meta.getColumnName(i); //henter column navnet
                        Object value = rs.getObject(i); //henter kolonnesvaret
                        row.put(name, value); //legger svaret med key og value i hashmap
                    }
                    results.add(row);
                }
            }
        } finally {
            close(rs); //lukker svaret
        }
        return results;
    }

    private static void close(Statement st) {
        try {
            if (st != null) {
                st.close(); //lukker statement. Statement er som en forbindelse over connection?
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close(); //resultset holder resultater for et statement
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials