execute Callable - Java java.sql

Java examples for java.sql:CallableStatement

Description

execute Callable

Demo Code


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

import java.sql.ResultSet;

import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static void executeCallable(Connection conn, String sql)
            throws Exception {

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

        CallableStatement cStmt = null;
        ResultSet rs = null;/* ww  w .  j a  v  a 2 s  .c  o  m*/

        try {
            cStmt = conn.prepareCall(sql);
            boolean hadResults = cStmt.execute();
            while (hadResults) {
                rs = cStmt.getResultSet();
                int columns = rs.getMetaData().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.getObject(i + 1));
                    }
                    System.out.println();
                }
                rs.close();
                hadResults = cStmt.getMoreResults();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            close(rs, cStmt);
        }

        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