count sql Results - Java JDBC

Java examples for JDBC:ResultSet

Description

count sql Results

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 int countResults(Connection conn, String sql)
            throws Exception {

        int count = 0;

        Statement stmt = null;//from w ww. j av  a 2 s  . c o m
        ResultSet rs = null;

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                count++;
            }
        } catch (Exception e) {
            throw e;
        } finally {
            close(rs, stmt);
        }

        return count;

    }

    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