print Result Set - Java java.sql

Java examples for java.sql:ResultSet

Description

print Result Set

Demo Code


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

public class Main {
    public static void printResultSet(Connection con, String sql,
            PrintWriter out) {/*www.java 2  s.  c om*/
        ResultSet rs;

        rs = getResultSet(con, sql);
        printResultSet(rs, out);
        try {
            rs.close();
            rs.getStatement().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void printResultSet(ResultSet rs, PrintWriter out) {
        printResultSet(rs, out, 0);
    }

    public static void printResultSet(ResultSet rs, PrintWriter out, int top) {
        int i, fieldNum, count;
        ResultSetMetaData rsMeta;

        try {
            count = 0;
            rsMeta = rs.getMetaData();
            fieldNum = rsMeta.getColumnCount();
            while (rs.next() && (count < top || top <= 0)) {
                for (i = 0; i < fieldNum; i++)
                    out.write(rs.getString(i + 1) + "\t");
                out.write("\n");
                out.flush();
                count++;
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ResultSet getResultSet(Connection con, String sql) {
        try {
            Statement st = con.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            ResultSet rs = st.executeQuery(sql);
            return rs;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void executeQuery(Connection con, String sql) {
        Statement st;

        try {
            st = con.createStatement();
            st.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials