print Table Column - Java JDBC

Java examples for JDBC:Table

Description

print Table Column

Demo Code


//package com.java2s;
import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static void printTableColumn(Connection conn, String sql)
            throws Exception {
        Statement stmt = null;//from   w  w  w  . jav  a2 s .co  m
        ResultSet rs = null;

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            ResultSetMetaData metadata = rs.getMetaData();
            int columns = metadata.getColumnCount();
            for (int i = 1; i <= columns; i++) {
                System.out.print(metadata.getColumnName(i) + "/"
                        + metadata.getColumnTypeName(i) + "  ");
            }
        } catch (Exception e) {
            throw e;
        } finally {
            close(rs, stmt);
        }
    }

    public static void executeQuery(Connection conn, String sql)
            throws Exception {

        System.out.println("Query SQL: " + sql);

        Statement stmt = null;
        ResultSet rs = null;

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            ResultSetMetaData metadata = rs.getMetaData();
            int columns = metadata.getColumnCount();
            for (int row = 1; rs.next(); row++) {
                System.out.print(row + ": ");
                for (int i = 0; i < columns; i++) {
                    if (i > 0) {
                        System.out.print(", ");
                    }
                    System.out.print(rs.getString(i + 1));
                }
                System.out.println();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            close(rs, stmt);
        }

        System.out.println();

    }

    public static void close(Connection conn) {

        if (null != conn) {
            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {

            }
        }
    }

    public static void close(Statement stmt) {

        if (null != stmt) {
            try {
                stmt.close();
                stmt = null;
            } catch (SQLException e) {

            }
        }
    }

    public static void close(ResultSet rs, Statement stmt) {

        if (null != rs) {
            try {
                rs.close();
                rs = null;
            } catch (SQLException e) {
            }
        }

        if (null != stmt) {
            try {
                stmt.close();
                stmt = null;
            } catch (SQLException e) {
            }
        }
    }
}

Related Tutorials