execute Query - Java JDBC

Java examples for JDBC:SQL Statement

Description

execute Query

Demo Code


//package com.java2s;

import java.sql.Connection;

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

public class Main {
    public static ResultSet executeQuery(Connection conn,
            String preparedQuery, Object... params) {
        ResultSet result = null;//from ww  w .j a  v  a 2  s  .c  om
        PreparedStatement stmt = null;
        try {
            stmt = conn.prepareStatement(preparedQuery);
            fillStatement(stmt, params);
            result = stmt.executeQuery();
        } catch (SQLException ex) {
            releaseDbConnection(conn, stmt, null);
            throw new RuntimeException(ex.getMessage(), ex);
        }
        return result;
    }

    public static void fillStatement(PreparedStatement stmt,
            Object... params) throws SQLException {
        if (params != null && params.length > 0) {
            ResultSetMetaData metadata = stmt.getMetaData();
            for (int i = 0; i < params.length; i++) {
                if (params[i] != null) {
                    stmt.setObject(i + 1, params[i]);
                } else {
                    try {
                        stmt.setNull(i + 1, metadata.getColumnType(i + 1));
                    } catch (NullPointerException ex) { // Oracle bug workaround
                        //            stmt.setNull(i + 1, java.sql.Types.VARCHAR);
                        stmt.setObject(i + 1, null);
                    }
                }
            }
        }
    }

    public static void releaseDbConnection(Connection conn, Statement stmt,
            ResultSet rset) {
        try {
            if (rset != null) {
                rset.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}

Related Tutorials