Example usage for java.sql ResultSetMetaData getColumnCount

List of usage examples for java.sql ResultSetMetaData getColumnCount

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnCount.

Prototype

int getColumnCount() throws SQLException;

Source Link

Document

Returns the number of columns in this ResultSet object.

Usage

From source file:com.termmed.statistics.Processor.java

/**
 * Prints the report./*from  www . ja  v  a  2  s  .  c om*/
 *
 * @param bw the bw
 * @param tableMap the table map
 * @throws Exception the exception
 */
private void printReport(BufferedWriter bw, OutputFileTableMap tableMap) throws Exception {

    SQLStatementExecutor executor = new SQLStatementExecutor(connection);

    for (SelectTableMap select : tableMap.getSelect()) {
        String query = "Select * from " + select.getTableName();
        if (executor.executeQuery(query, null)) {
            ResultSet rs = executor.getResultSet();

            if (rs != null) {
                ResultSetMetaData meta = rs.getMetaData();
                while (rs.next()) {
                    for (int i = 0; i < meta.getColumnCount(); i++) {
                        if (rs.getObject(i + 1) != null) {
                            bw.append(rs.getObject(i + 1).toString());
                        } else {
                            bw.append("");
                        }
                        if (i + 1 < meta.getColumnCount()) {
                            bw.append(",");
                        } else {
                            bw.append("\r\n");
                        }
                    }
                }

                meta = null;
                rs.close();
            }
        }
    }
    executor = null;
}

From source file:Statement.Statement.java

private void loadView() {
    fieldData = new Vector<>();
    fieldNames = new Vector();
    //Display Revenue
    try {/*from  w ww .j  av  a 2 s  . co  m*/
        PreparedStatement st = cnn
                .prepareStatement("SELECT TypeName,Quantity FROM Revenue where ShopID = ? and Date = ?");
        st.setString(1, code);
        st.setString(2, date);
        ResultSet rs = st.executeQuery();

        ResultSetMetaData meta = rs.getMetaData();
        for (int i = 1; i <= meta.getColumnCount(); i++) {
            fieldNames.add(meta.getColumnName(i));
        }
        while (rs.next()) {
            Vector tmp = new Vector();
            tmp.add(rs.getString(1));
            tmp.add(rs.getInt(2));
            fieldData.add(tmp);
        }
        model = new DefaultTableModel(fieldData, fieldNames);
        tbl.setModel(model);
    } catch (Exception e) {
    }
}

From source file:com.ws.WS_TCS201.java

@Path("/GetDETAIL/{com}/{account}")
@JSONP(queryParam = "callback")
@GET//from www  .ja va 2  s.c o m
@Produces({ "application/x-javascript" })
public String GetDETAIL(@QueryParam("callback") String callback, @PathParam("com") String com,
        @PathParam("account") String account) {

    JSONObject obj1 = new JSONObject();
    LinkedList l1 = new LinkedList();

    PreparedStatement prepStmt = null;

    try {
        //

        String cSQL = " SELECT tceemp, tceapd, tceall, tcetkb, tcetkt FROM TCSTCE "
                + " WHERE tcecom= ? AND tceemp= ? " + " ORDER BY tceapd DESC";
        prepStmt = connection.prepareStatement(cSQL);
        prepStmt.setString(1, com);
        prepStmt.setString(2, account);
        ResultSet result = prepStmt.executeQuery();

        if (result.next()) {
            LinkedHashMap m1 = new LinkedHashMap();

            Object obj = result.getObject(2);

            //?
            m1.put("arrive", obj.toString().substring(0, 4) + "/" + obj.toString().substring(4, 6) + "/"
                    + obj.toString().substring(6, 8));

            //
            if (Integer.parseInt(obj.toString()) < 20100913) {
                m1.put("start", "01/01");
            } else {
                m1.put("start", obj.toString().substring(4, 6) + "/" + obj.toString().substring(6, 8));
            }

            //
            obj = result.getObject(3);
            m1.put("allday", obj.toString());

            l1.add(m1);
        }
        obj1.put("base", l1);

        //
        result.close();
        l1.clear();

        cSQL = " SELECT tch.tchyer,CONCAT(tch.tchtcd,\" - \",tcc.tcctxt) AS tcdnam,tch.tchdst,tch.tchded,tch.tchday,tch.tchlst,tch.tchtxt,tch.tchtcd,tch.tchtck, "
                + "        IFNULL(tchgrp.maxtck,\"\") AS maxtck, IFNULL(tchgrp.maxdst,0) AS maxdst "
                + " FROM TCSTCH AS tch "
                + " LEFT JOIN (SELECT DISTINCT tcecom,tceemp,tcenam FROM TCSTCE) AS tce "
                + "        ON tcecom=tchcom AND tce.tceemp=tch.tchemp "
                + " LEFT JOIN (SELECT tcctcd, tcctxt FROM TCSTCC ) AS tcc "
                + "        ON tcc.tcctcd=tch.tchtcd "
                + " LEFT JOIN ( SELECT tchcom,tchemp,tchyer,max(tchtck) AS maxtck,max(tchdst) AS maxdst FROM TCSTCH "
                + "             WHERE tchtcd not in (\"B\",\"T\",\"M\",\"F\",\"W\") "
                + "             GROUP BY tchcom,tchemp,tchyer ) AS tchgrp "
                + "        ON tch.tchcom = tchgrp.tchcom AND tch.tchemp = tchgrp.tchemp "
                + "       AND tch.tchyer = tchgrp.tchyer " + " WHERE tch.tchcom= ? AND tch.tchemp= ? "
                + "   AND tcc.tcctcd NOT IN (\"A\",\"L\",\"R\",\"J\",\"N\") "
                + "   AND tch.tchmrk=\" \" AND tch.tchyer >= 2014 " + " ORDER BY tch.tchemp,tch.tchdst DESC ";
        //"       tchmrk=\" \" AND tchyer >= CONV( SUBSTR(NOW( ),1,4),10,10) -1 " +
        prepStmt = connection.prepareStatement(cSQL);
        prepStmt.setString(1, com);
        prepStmt.setString(2, account);
        result = prepStmt.executeQuery();
        ResultSetMetaData rsmd = result.getMetaData();
        int numcols = rsmd.getColumnCount();

        while (result.next()) {
            LinkedHashMap m1 = new LinkedHashMap();
            for (int j = 1; j <= numcols; j++) {
                Object obj = result.getObject(j);
                m1.put(rsmd.getColumnName(j).toString(), obj.toString());
            }
            Object obj = result.getObject("tchtcd");
            String chk1 = obj.toString();
            obj = result.getObject("tchtck");
            String chk2 = obj.toString();
            obj = result.getObject("tchdst");
            String chk3 = obj.toString();
            obj = result.getObject("maxdst");
            String chk4 = obj.toString();
            if (((chk1.equals("M") || chk1.equals("F") || chk1.equals("W") || chk1.equals("B")
                    || chk1.equals("T")) && chk2.equals("-"))
                    || (!chk1.equals("M") && !chk1.equals("F") && !chk1.equals("W") && !chk1.equals("B")
                            && !chk1.equals("T") && chk3.equals(chk4))) {
                m1.put("edit", "Y");
            } else {
                m1.put("edit", "N");
            }
            l1.add(m1);
        }
        obj1.put("detail", l1);
    } catch (SQLException e) {
        prepStmt = null;
        e.printStackTrace();
    } catch (Exception e) {
        prepStmt = null;
        e.printStackTrace();
    }
    return obj1.toString();
}

From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java

/**
 * Similar to the same method in original pubtest utility, but doesn't throw an exception if 0 rows are returned
 * and uses existing(established) JDBC connection corresponding to its published datasource name.
 * //from  w ww  . j  a  va  2s. com
 */
public static String executeProcedure(RegressionItem item, HashMap<String, Connection> cisConnections,
        String outputFile, String delimiter, String printOutputType) throws CompositeException {
    // Set the command and action name
    String command = "executeProcedure";
    String actionName = "REGRESSION_TEST";

    int rows = 0;
    String result = null;
    Connection conn = null;
    CallableStatement stmt = null;
    ResultSet rs = null;
    start = System.currentTimeMillis();
    long firstRowLatency = 0L;

    // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
    if (CommonUtils.isExecOperation()) {
        try {
            conn = getJdbcConnection(item.database, cisConnections); // don't need to check for null here.

            String URL = null;
            String userName = null;
            if (conn.getMetaData() != null) {
                if (conn.getMetaData().getURL() != null)
                    URL = conn.getMetaData().getURL();
                if (conn.getMetaData().getUserName() != null)
                    userName = conn.getMetaData().getUserName();
            }
            RegressionManagerUtils.printOutputStr(printOutputType, "debug",
                    "RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delimiter, printOutputType).  item.database="
                            + item.database + "  cisConnections.URL=" + URL + "  cisConnections.userName="
                            + userName + "  outputFile=" + outputFile + "  delimiter=" + delimiter
                            + "  printOutputType=" + printOutputType,
                    "");
            RegressionManagerUtils.printOutputStr(printOutputType, "debug",
                    "DEBUG: connection to DB successful", "");

            String query = item.input.replaceAll("\n", " ");
            // Convert a CALL statement into a SELECT * FROM statement

            // { CALL SCH1.LookupProduct( 3 ) } --> SCH1.LookupProduce( 3 )
            if (query.toUpperCase().contains("CALL")) {
                query = "SELECT * FROM " + RegressionManagerUtils.getProcedure(query);
                ;
            }

            // Prepare the query
            stmt = (CallableStatement) conn.prepareCall(query);

            // Register output parameter types
            for (int i = 0; i < item.outTypes.length; i++) {
                if (!"-".equals(item.outTypes[i])) {
                    int jdbcType = -1;
                    try {
                        jdbcType = Types.class.getField(item.outTypes[i]).getInt(null);
                    } catch (Exception e) {
                        RegressionManagerUtils.error(item.lineNum, item.outTypes[i],
                                "No such JDBC type in java.sql.Types");
                    }
                    stmt.registerOutParameter(i + 1, jdbcType);
                }
            }
            stmt.executeQuery();

            // Print scalars
            ParameterMetaData pmd = stmt.getParameterMetaData();
            int params = pmd.getParameterCount();
            boolean addSep = false;
            String content = "";
            for (int i = 0; i < params; i++) {
                if (addSep) {
                    content += delimiter;
                }
                if (stmt.getObject(i + 1) != null)
                    content += stmt.getObject(i + 1).toString();
                else
                    content += "";
                addSep = true;
            }
            if (outputFile != null)
                CommonUtils.appendContentToFile(outputFile, content);
            RegressionManagerUtils.printOutputStr(printOutputType, "results", content, "");

            // Get the result cursor and metadata cursor        
            rs = stmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columns = rsmd.getColumnCount();

            // Get the column metadata                      
            addSep = false;
            content = "";
            for (int i = 0; i < columns; i++) {
                if (addSep) {
                    content += delimiter;
                }
                if (rsmd.getColumnName(i + 1) != null)
                    content += rsmd.getColumnName(i + 1).toString();
                else
                    content += "";
                addSep = true;
            }
            if (outputFile != null)
                CommonUtils.appendContentToFile(outputFile, content);
            RegressionManagerUtils.printOutputStr(printOutputType, "results", content, "");

            // Print cursors
            boolean firstRow = true;
            while (rs != null) {
                // Read the values
                while (rs.next()) {
                    if (firstRow) {
                        firstRowLatency = System.currentTimeMillis() - start;
                        firstRow = false;
                    }
                    addSep = false;
                    content = "";
                    for (int i = 0; i < columns; i++) {
                        if (addSep) {
                            content += delimiter;
                        }
                        if (rs.getObject(i + 1) != null)
                            content += rs.getObject(i + 1).toString();
                        else
                            content += "";
                        addSep = true;
                    }
                    if (outputFile != null)
                        CommonUtils.appendContentToFile(outputFile, content);
                    RegressionManagerUtils.printOutputStr(printOutputType, "results", content, "");
                    rows++;
                }
                stmt.getMoreResults();
                rs = stmt.getResultSet();
            }
        } catch (SQLException e) {
            throw new CompositeException("executeProcedure(): " + e.getMessage());
        } catch (Exception e) {
            throw new CompositeException("executeProcedure(): " + e.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                rs = null;
                stmt = null;
                throw new CompositeException(
                        "executeProcedure(): unable to close ResultSet or Statement" + e.getMessage());
            }
        }
        RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeProcedure()", "");
    } else {
        logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                + "] WAS NOT PERFORMED.\n");
    }

    // <rows>:<firstRowLatency>
    result = "" + rows + ":" + firstRowLatency;
    return result;
    /* Note: to process this result string on the client invocation side use the following pattern:
     * 
     *    String result = RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delim, printOutputType, "results");
       String results[] = result.split(":");
       if (results.length > 1) {
          rowCount = Integer.valueOf(results[0]);
             firstRowLatency.addAndGet(Long.parseLong(results[1]));                    
       }                  
     */
}

From source file:controlador.Peticiones.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww  w .  ja  va2  s.co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //response.setContentType("text/html;charset=UTF-8");
    String target, op, action, view;

    target = request.getParameter("target");
    op = request.getParameter("op");

    if (target.equals("login")) {

        bd = new ControlDB();
        bd.cargarDriver();
        bd.conectar();
        String login = request.getParameter("login");
        String pass = request.getParameter("password");
        ResultSet r = bd.ejecutarSelect("SELECT * FROM roles WHERE nombreRol='" + login + "' AND passRol='"
                + Auxiliar.encriptarPass(pass) + "'");
        JSONObject objetoJSON = new JSONObject();
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            if (r != null && r.next()) {
                objetoJSON.put("r", "1");
                out.print(objetoJSON);
            } else {
                objetoJSON.put("r", "0");
                out.print(objetoJSON);
            }
        } catch (SQLException ex) {

        } catch (JSONException ex) {

        }
    } else {
        if (target.equals("pedido")) {
            bd = new ControlDB();
            bd.cargarDriver();
            bd.conectar();
            String s = request.getParameter("datos");
            JSONTokener token = new JSONTokener(s);
            JSONArray ar = null;
            ArrayList<Producto> productos = new ArrayList();
            try {
                ar = new JSONArray(token);
                for (int i = 0; i < ar.length(); i++) {
                    agregarProducto(ar.getJSONObject(i).getInt("idMesa"),
                            ar.getJSONObject(i).getInt("idProducto"));
                    ResultSet rs = bd.ejecutarSelect("SELECT nombreProducto from productos where idProducto = "
                            + ar.getJSONObject(i).getInt("idProducto"));
                    rs.next();
                    String nombre = rs.getString("nombreProducto");
                    Producto pr = new Producto(nombre);
                    if (productos.contains(pr)) {
                        int pos = productos.indexOf(pr);
                        productos.get(pos).sumaCantidad();
                    } else {
                        productos.add(new Producto(nombre));
                    }
                }
                ResultSet nombreMesa = bd.ejecutarSelect(
                        "SELECT nombreMesa, nombreZona from mesas inner join zona on idZona=Zona_Idzona where idmesa="
                                + ar.getJSONObject(0).getInt("idMesa"));
                nombreMesa.next();
                String nombre = nombreMesa.getString("nombreMesa") + " " + nombreMesa.getString("nombreZona");
                Comanda comanda = new Comanda(productos, nombre);
                System.out.println("Ticket: \n" + comanda.contenidoComanda);
                Auxiliar.imprimir(comanda.contenidoComanda);
            } catch (JSONException ex) {
                System.out.println("Error JSON " + ex.toString());
            } catch (SQLException ex) {
                System.out.println("Error SQL " + ex.toString());
            }

            // Crear un el objeto para enviar a comanda para imprimir, implementar

            response.setHeader("Content-Type", "application/json");
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            JSONObject obj = new JSONObject();
            try {
                obj.put("r", "recibido");
            } catch (JSONException ex) {

            }
            out.print(obj);
            out.flush();
        } else {
            if (target.equals("mesas")) {
                bd = new ControlDB();
                bd.cargarDriver();
                bd.conectar();

                ResultSet r = bd.ejecutarSelect(
                        "SELECT mesas.idMesa, nombreMesa, nombreZona FROM mesas inner join zona on idzona = Zona_idZona");

                JSONArray array = new JSONArray();
                ResultSetMetaData rsMetaData = null;
                int columns = 0;
                try {
                    rsMetaData = r.getMetaData();
                    columns = rsMetaData.getColumnCount();
                } catch (SQLException ex) {

                }

                try {
                    while (r.next()) {
                        JSONObject objetoJSON = new JSONObject();
                        for (int i = 1; i <= columns; i++) {
                            objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i));
                        }
                        System.out.println(objetoJSON + "\n");
                        array.put(objetoJSON);
                    }
                } catch (SQLException ex) {

                } catch (JSONException ex) {

                }
                response.setHeader("Content-Type", "application/json");
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                PrintWriter out = response.getWriter();
                out.print(array);
                out.flush();
            } else {
                if (target.equals("familias")) {
                    bd = new ControlDB();
                    bd.cargarDriver();
                    bd.conectar();

                    ResultSet r = bd.ejecutarSelect(
                            "SELECT idFamilia, nombreFamilia FROM `familias` order by idFamilia");

                    JSONArray array = new JSONArray();
                    ResultSetMetaData rsMetaData = null;
                    int columns = 0;
                    try {
                        rsMetaData = r.getMetaData();
                        columns = rsMetaData.getColumnCount();
                    } catch (SQLException ex) {

                    }

                    try {
                        while (r.next()) {
                            JSONObject objetoJSON = new JSONObject();
                            for (int i = 1; i <= columns; i++) {
                                objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i));
                            }
                            array.put(objetoJSON);
                        }
                    } catch (SQLException ex) {

                    } catch (JSONException ex) {
                        ;
                    }
                    response.setHeader("Content-Type", "application/json");
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    PrintWriter out = response.getWriter();
                    out.print(array);
                    out.flush();
                } else {
                    if (target.equals("productos")) {
                        bd = new ControlDB();
                        bd.cargarDriver();
                        bd.conectar();

                        ResultSet r = bd.ejecutarSelect(
                                "SELECT idProducto, nombreProducto,fotoProducto , precioProducto, Familias_idFamilias FROM productos order by idProducto");

                        JSONArray array = new JSONArray();
                        ResultSetMetaData rsMetaData = null;
                        int columns = 0;
                        try {
                            rsMetaData = r.getMetaData();
                            columns = rsMetaData.getColumnCount();
                        } catch (SQLException ex) {

                        }

                        try {
                            while (r.next()) {
                                JSONObject objetoJSON = new JSONObject();
                                for (int i = 1; i <= columns; i++) {
                                    objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i));
                                }
                                array.put(objetoJSON);
                            }
                        } catch (SQLException ex) {

                        } catch (JSONException ex) {

                        }
                        response.setHeader("Content-Type", "application/json");
                        response.setContentType("application/json");
                        response.setCharacterEncoding("UTF-8");
                        PrintWriter out = response.getWriter();
                        out.print(array);
                        out.flush();
                    }
                }
            }
        }
    }

}

From source file:CSVWriter.java

/**
 * Writes the entire ResultSet to a CSV file.
 *
 * The caller is responsible for closing the ResultSet.
 *
 * @param rs the recordset to write/*w  ww.j  a v  a2 s.c o m*/
 * @param includeColumnNames true if you want column names in the output, false otherwise
 *
 */
public void writeAll(java.sql.ResultSet rs, boolean includeColumnNames)  throws SQLException, IOException {
      
  ResultSetMetaData metadata = rs.getMetaData();
      
      
  if (includeColumnNames) {
  writeColumnNames(metadata);
}

  int columnCount =  metadata.getColumnCount();
      
  while (rs.next())
  {
      String[] nextLine = new String[columnCount];
          
      for (int i = 0; i < columnCount; i++) {
    nextLine[i] = getColumnValue(rs, metadata.getColumnType(i + 1), i + 1);
  }
          
    writeNext(nextLine);
  }
}

From source file:org.jfree.data.jdbc.JDBCXYDataset.java

/**
 * ExecuteQuery will attempt execute the query passed to it against the
 * provided database connection.  If connection is null then no action is
 * taken./*  w w  w .j ava  2  s  . c  om*/
 *
 * The results from the query are extracted and cached locally, thus
 * applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param  query  the query to be executed.
 * @param  con  the connection the query is to be executed against.
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    if (con == null) {
        throw new SQLException("There is no database to execute the query.");
    }

    ResultSet resultSet = null;
    Statement statement = null;
    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int numberOfColumns = metaData.getColumnCount();
        int numberOfValidColumns = 0;
        int[] columnTypes = new int[numberOfColumns];
        for (int column = 0; column < numberOfColumns; column++) {
            try {
                int type = metaData.getColumnType(column + 1);
                switch (type) {

                case Types.NUMERIC:
                case Types.REAL:
                case Types.INTEGER:
                case Types.DOUBLE:
                case Types.FLOAT:
                case Types.DECIMAL:
                case Types.BIT:
                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP:
                case Types.BIGINT:
                case Types.SMALLINT:
                    ++numberOfValidColumns;
                    columnTypes[column] = type;
                    break;
                default:
                    columnTypes[column] = Types.NULL;
                    break;
                }
            } catch (SQLException e) {
                columnTypes[column] = Types.NULL;
                throw e;
            }
        }

        if (numberOfValidColumns <= 1) {
            throw new SQLException("Not enough valid columns where generated by query.");
        }

        /// First column is X data
        this.columnNames = new String[numberOfValidColumns - 1];
        /// Get the column names and cache them.
        int currentColumn = 0;
        for (int column = 1; column < numberOfColumns; column++) {
            if (columnTypes[column] != Types.NULL) {
                this.columnNames[currentColumn] = metaData.getColumnLabel(column + 1);
                ++currentColumn;
            }
        }

        // Might need to add, to free memory from any previous result sets
        if (this.rows != null) {
            for (int column = 0; column < this.rows.size(); column++) {
                ArrayList row = (ArrayList) this.rows.get(column);
                row.clear();
            }
            this.rows.clear();
        }

        // Are we working with a time series.
        switch (columnTypes[0]) {
        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            this.isTimeSeries = true;
            break;
        default:
            this.isTimeSeries = false;
            break;
        }

        // Get all rows.
        // rows = new ArrayList();
        while (resultSet.next()) {
            ArrayList newRow = new ArrayList();
            for (int column = 0; column < numberOfColumns; column++) {
                Object xObject = resultSet.getObject(column + 1);
                switch (columnTypes[column]) {
                case Types.NUMERIC:
                case Types.REAL:
                case Types.INTEGER:
                case Types.DOUBLE:
                case Types.FLOAT:
                case Types.DECIMAL:
                case Types.BIGINT:
                case Types.SMALLINT:
                    newRow.add(xObject);
                    break;

                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP:
                    newRow.add(new Long(((Date) xObject).getTime()));
                    break;
                case Types.NULL:
                    break;
                default:
                    System.err.println("Unknown data");
                    columnTypes[column] = Types.NULL;
                    break;
                }
            }
            this.rows.add(newRow);
        }

        /// a kludge to make everything work when no rows returned
        if (this.rows.size() == 0) {
            ArrayList newRow = new ArrayList();
            for (int column = 0; column < numberOfColumns; column++) {
                if (columnTypes[column] != Types.NULL) {
                    newRow.add(new Integer(0));
                }
            }
            this.rows.add(newRow);
        }

        /// Determine max and min values.
        if (this.rows.size() < 1) {
            this.maxValue = 0.0;
            this.minValue = 0.0;
        } else {
            ArrayList row = (ArrayList) this.rows.get(0);
            this.maxValue = Double.NEGATIVE_INFINITY;
            this.minValue = Double.POSITIVE_INFINITY;
            for (int rowNum = 0; rowNum < this.rows.size(); ++rowNum) {
                row = (ArrayList) this.rows.get(rowNum);
                for (int column = 1; column < numberOfColumns; column++) {
                    Object testValue = row.get(column);
                    if (testValue != null) {
                        double test = ((Number) testValue).doubleValue();

                        if (test < this.minValue) {
                            this.minValue = test;
                        }
                        if (test > this.maxValue) {
                            this.maxValue = test;
                        }
                    }
                }
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                // TODO: is this a good idea?
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                // TODO: is this a good idea?
            }
        }
    }

}

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testPreparedStatementMetaData() throws SQLException {
    PreparedStatement prep = conn.prepareStatement("select * from table(x int = ?, name varchar = ?)");
    ResultSetMetaData meta = prep.getMetaData();
    assertEquals(2, meta.getColumnCount());
    assertEquals("INTEGER", meta.getColumnTypeName(1));
    assertEquals("VARCHAR", meta.getColumnTypeName(2));
    prep = conn.prepareStatement("call 1");
    meta = prep.getMetaData();//from  w  w  w .j a v a  2s  .  c o  m
    assertEquals(1, meta.getColumnCount());
    assertEquals("INTEGER", meta.getColumnTypeName(1));
}

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

/**
 * The positions in the returned array represent column numbers. The values stored at each
 * position represent the index in the <code>PropertyDescriptor[]</code> for the bean property
 * that matches the column name. If no bean property was found for a column, the position is set
 * to <code>PROPERTY_NOT_FOUND</code>.
 *
 * @param rsmd The <code>ResultSetMetaData</code> containing column information.
 *
 * @param props The bean property descriptors.
 *
 * @throws SQLException if a database access error occurs
 *
 * @return An int[] with column index to property index mappings. The 0th element is meaningless
 * because JDBC column indexing starts at 1.
 *//*from  ww w  .  j  a  v  a  2 s.  c o  m*/
private int[] mapColumnsToProperties(ResultSetMetaData rsmd, PropertyDescriptor[] props) throws SQLException {

    int cols = rsmd.getColumnCount();
    int[] columnToProperty = new int[cols + 1];

    Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);

    for (int col = 1; col <= cols; col++) {

        String columnName = rsmd.getColumnLabel(col);

        for (int i = 0; i < props.length; i++) {

            Column columnAnnotation = props[i].getReadMethod().getAnnotation(Column.class);

            if (columnAnnotation == null) {

                //'_'
                if (columnName.replace("_", "").equalsIgnoreCase(props[i].getName())) {

                    columnToProperty[col] = i;
                    break;
                }
            } else if (columnName.equalsIgnoreCase(columnAnnotation.value())
                    || columnName.equalsIgnoreCase(columnAnnotation.name())) {

                columnToProperty[col] = i;
                break;
            }

        }
    }

    return columnToProperty;
}

From source file:com.iih5.smartorm.model.Model.java

/**
 * Model//from  www .  ja  va2  s.c  om
 *
 * @param columns        ?? columns="id,name,age"
 * @param conditions     ? conditions="user_id=? and age=?"
 * @param conditionParas ??
 * @param <T>
 * @return Model
 * @
 */
<T> List<T> queryList(String columns, String conditions, Object[] conditionParas) {
    String sql = DefaultDialect.getDialect().forModelFindBy(table, columns, conditions);
    final Set<String> columnMeta = new HashSet<String>();
    return jdbc.query(sql, conditionParas, new RowMapper<T>() {
        public T mapRow(ResultSet rs, int rowNum) throws SQLException {
            try {
                if (columnMeta.size() == 0) {
                    for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
                        String column = rs.getMetaData().getColumnLabel(i + 1);
                        columnMeta.add(column);
                    }
                }
                Model<?> mModel = getUsefulClass().newInstance();
                Field[] fields = mModel.getClass().getFields();
                if (fields.length > 0) {
                    for (Field f : fields) {
                        if (columnMeta.contains(f.getName())) {
                            f.set(mModel, rs.getObject(f.getName()));
                        }
                    }
                } else {
                    ResultSetMetaData rsmd = rs.getMetaData();
                    int columnCount = rsmd.getColumnCount();
                    Map<String, Object> attrs = mModel.getAttrs();
                    for (int i = 1; i <= columnCount; i++) {
                        Object value = rs.getObject(i);
                        if (value != null) {
                            attrs.put(rsmd.getColumnLabel(i), value);
                        }
                    }
                }
                return (T) mModel;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });
}