Java SQL Query query(Connection conn, String sql, Object[] params, Class beanClass)

Here you can find the source of query(Connection conn, String sql, Object[] params, Class beanClass)

Description

query

License

Apache License

Declaration

public static <T> T query(Connection conn, String sql, Object[] params, Class<T> beanClass) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Field;
import java.sql.Connection;

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

public class Main {
    public static <T> T query(Connection conn, String sql, Object[] params, Class<T> beanClass) {
        PreparedStatement ps = null;
        try {// w ww  . ja v a 2  s. c  om
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            ResultSet rs = ps.executeQuery();
            Field[] fields = beanClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
            }
            T t = beanClass.newInstance();
            while (rs != null && rs.next()) {
                for (Field f : fields) {
                    String name = f.getName();
                    Object value = rs.getObject(name);
                    f.set(t, value);
                }
            }
            return t;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                    ps = null;
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void close(ResultSet rs, Statement st, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        rs = null;
        st = null;
        conn = null;
    }
}

Related

  1. executeSafeQuery( Connection conn, String sql)
  2. executeStatement(Connection connection, String query)
  3. getSqlQuery(Statement statement, Object[] args)
  4. getStatement(Connection con, String query, Object... bits)
  5. query(Connection conn, String sql)
  6. query(Connection connection, String sql, boolean isClose, Object... params)
  7. queryForList(Connection conn, String sql, int limit)
  8. queryObjectList(Connection con, String sql, Class objClass)
  9. queryProjectTicketIdFromTicketId(Connection db, int ticketId)