Example usage for java.sql ResultSet getObject

List of usage examples for java.sql ResultSet getObject

Introduction

In this page you can find the example usage for java.sql ResultSet getObject.

Prototype

Object getObject(String columnLabel) throws SQLException;

Source Link

Document

Gets the value of the designated column in the current row of this ResultSet object as an Object in the Java programming language.

Usage

From source file:cherry.foundation.etl.ExtractorResultSetExtractor.java

@Override
public Long extractData(ResultSet rs) throws SQLException, DataAccessException {
    try {//  www. jav  a 2  s  .co m

        ResultSetMetaData metaData = rs.getMetaData();
        Column[] col = new Column[metaData.getColumnCount()];
        for (int i = 1; i <= col.length; i++) {
            col[i - 1] = new Column();
            col[i - 1].setType(metaData.getColumnType(i));
            col[i - 1].setLabel(metaData.getColumnLabel(i));
        }

        consumer.begin(col);

        long count;
        for (count = 0L; rs.next(); count++) {

            Object[] record = new Object[col.length];
            for (int i = 1; i <= record.length; i++) {
                record[i - 1] = rs.getObject(i);
            }

            consumer.consume(record);
            limiter.tick();
        }

        consumer.end();
        return count;

    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 * Write a GeoJSON feature.//from   w ww.ja v a 2  s.co m
 *
 * Features in GeoJSON contain a geometry object and additional properties,
 * and a feature collection represents a list of features.
 *
 * A complete GeoJSON data structure is always an object (in JSON terms). In
 * GeoJSON, an object consists of a collection of name/value pairs -- also
 * called members. For each member, the name is always a string. Member
 * values are either a string, number, object, array or one of the literals:
 * true, false, and null. An array consists of elements where each element
 * is a value as described above.
 *
 * Syntax:
 *
 * { "type": "Feature", "geometry":{"type": "Point", "coordinates": [102.0,
 * 0.5]}, "properties": {"prop0": "value0"} }
 *
 * @param writer
 * @param resultSetMetaData
 * @param geoFieldIndex
 */
private void writeFeature(JsonGenerator jsonGenerator, ResultSet rs, int geoFieldIndex)
        throws IOException, SQLException {
    // feature header
    jsonGenerator.writeStartObject();
    jsonGenerator.writeStringField("type", "Feature");
    //Write the first geometry
    writeGeometry((Geometry) rs.getObject(geoFieldIndex), jsonGenerator);
    //Write the properties
    writeProperties(jsonGenerator, rs);
    // feature footer
    jsonGenerator.writeEndObject();
}

From source file:ca.nrc.cadc.vos.server.NodeMapper.java

/**
 * Map the row to the appropriate type of node object.
 * @param rs/* w w w  .  ja v a 2 s . c  o m*/
 * @param row
 * @return a Node
 * @throws SQLException
 */
public Object mapRow(ResultSet rs, int row) throws SQLException {

    long nodeID = rs.getLong("nodeID");
    String name = rs.getString("name");
    String type = rs.getString("type");
    String busyString = rs.getString("busyState");
    String groupRead = rs.getString("groupRead");
    String groupWrite = rs.getString("groupWrite");
    boolean isPublic = rs.getBoolean("isPublic");
    boolean isLocked = rs.getBoolean("isLocked");

    Object ownerObject = rs.getObject("ownerID");
    String contentType = rs.getString("contentType");
    String contentEncoding = rs.getString("contentEncoding");
    String link = null;

    Long contentLength = null;
    Object o = rs.getObject("contentLength");
    if (o != null) {
        Number n = (Number) o;
        contentLength = new Long(n.longValue());
    }
    log.debug("readNode: contentLength = " + contentLength);

    Object contentMD5 = rs.getObject("contentMD5");
    Date lastModified = rs.getTimestamp("lastModified", cal);

    String path = basePath + "/" + name;
    VOSURI vos;
    try {
        vos = new VOSURI(new URI("vos", authority, path, null, null));
    } catch (URISyntaxException bug) {
        throw new RuntimeException("BUG - failed to create vos URI", bug);
    }

    Node node;
    if (NodeDAO.NODE_TYPE_CONTAINER.equals(type)) {
        node = new ContainerNode(vos);
    } else if (NodeDAO.NODE_TYPE_DATA.equals(type)) {
        node = new DataNode(vos);
        ((DataNode) node).setBusy(NodeBusyState.getStateFromValue(busyString));
    } else if (NodeDAO.NODE_TYPE_LINK.equals(type)) {
        link = rs.getString("link");
        try {
            node = new LinkNode(vos, new URI(link));
        } catch (URISyntaxException bug) {
            throw new RuntimeException("BUG - failed to create link URI", bug);
        }
    } else {
        throw new IllegalStateException("Unknown node database type: " + type);
    }

    NodeID nid = new NodeID();
    nid.id = nodeID;
    nid.ownerObject = ownerObject;
    node.appData = nid;

    if (contentType != null && contentType.trim().length() > 0) {
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_TYPE, contentType));
    }

    if (contentEncoding != null && contentEncoding.trim().length() > 0) {
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_CONTENTENCODING, contentEncoding));
    }

    if (contentLength != null)
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_CONTENTLENGTH, contentLength.toString()));
    else
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_CONTENTLENGTH, "0"));

    if (contentMD5 != null && contentMD5 instanceof byte[]) {
        byte[] md5 = (byte[]) contentMD5;
        if (md5.length < 16) {
            byte[] tmp = md5;
            md5 = new byte[16];
            System.arraycopy(tmp, 0, md5, 0, tmp.length);
            // extra space is init with 0
        }
        String contentMD5String = HexUtil.toHex(md5);
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_CONTENTMD5, contentMD5String));
    }
    if (lastModified != null) {
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_DATE, dateFormat.format(lastModified)));
    }
    if (groupRead != null && groupRead.trim().length() > 0) {
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_GROUPREAD, groupRead));
    }
    if (groupWrite != null && groupWrite.trim().length() > 0) {
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_GROUPWRITE, groupWrite));
    }
    node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_ISPUBLIC, isPublic ? "true" : "false"));

    if (isLocked)
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_ISLOCKED, isLocked ? "true" : "false"));

    // set the read-only flag on the properties
    for (String propertyURI : VOS.READ_ONLY_PROPERTIES) {
        int propertyIndex = node.getProperties().indexOf(new NodeProperty(propertyURI, ""));
        if (propertyIndex != -1) {
            node.getProperties().get(propertyIndex).setReadOnly(true);
        }
    }
    log.debug("read: " + node.getUri() + "," + node.appData);
    return node;
}

From source file:com.adaptris.core.services.jdbc.JdbcDataCaptureServiceImpl.java

protected void saveKeys(AdaptrisMessage msg, Statement stmt) throws SQLException {
    ResultSet rs = null;
    Statement savedKeysQuery = null;

    try {//w  w w  .j  a  va 2s.  c o  m
        if (saveReturnedKeys()) {
            if (!actor.isOldJbc()) {
                rs = stmt.getGeneratedKeys();
                rs.next();
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    String name = rsmd.getColumnName(i);
                    String value = rs.getObject(name).toString();
                    msg.addMetadata(name, value);
                }
            } else {
                savedKeysQuery = createStatement(actor.getSqlConnection());
                rs = savedKeysQuery.executeQuery(
                        "select max(" + saveReturnedKeysColumn + ") from " + saveReturnedKeysTable + ";");
                rs.next();
                String value = rs.getObject(saveReturnedKeysColumn).toString();
                msg.addMetadata(saveReturnedKeysColumn, value);
            }
        }
    } finally {
        JdbcUtil.closeQuietly(savedKeysQuery);
        JdbcUtil.closeQuietly(rs);
    }
}

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

public void testSetObject() throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("CREATE TABLE TEST(C CHAR(1))");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?)");
    prep.setObject(1, 'x');
    prep.execute();//from w  ww.j  a  va 2  s. co  m
    stat.execute("DROP TABLE TEST");
    stat.execute("CREATE TABLE TEST(ID INT, DATA BINARY, JAVA OTHER)");
    prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?)");
    prep.setInt(1, 1);
    prep.setObject(2, 11);
    prep.setObject(3, null);
    prep.execute();
    prep.setInt(1, 2);
    prep.setObject(2, 101, Types.OTHER);
    prep.setObject(3, 103, Types.OTHER);
    prep.execute();
    PreparedStatement p2 = conn.prepareStatement("SELECT * FROM TEST ORDER BY ID");
    ResultSet rs = p2.executeQuery();
    rs.next();
    Object o = rs.getObject(2);
    assertTrue(o instanceof byte[]);
    assertTrue(rs.getObject(3) == null);
    rs.next();
    o = rs.getObject(2);
    assertTrue(o instanceof byte[]);
    o = rs.getObject(3);
    assertTrue(o instanceof Integer);
    assertEquals(103, ((Integer) o).intValue());
    assertFalse(rs.next());
    stat.execute("DROP TABLE TEST");
}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

/**
 * Test the {@code Set} object in Cassandra.
 *///  www . ja  v  a2 s  . c o m
@Test
public void testObjectSet() throws Exception {
    Statement stmt = con.createStatement();

    // Create the target Column family
    String createCF = "CREATE COLUMNFAMILY t65 (key text PRIMARY KEY," + "int1 int, " + "int2 int, "
            + "intset  set<int> " + ") ;";

    stmt.execute(createCF);
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));

    Statement statement = con.createStatement();
    String insert = "INSERT INTO t65 (key, int1,int2,intset) VALUES ('key1',1,100,{10,20,30,40});";
    statement.executeUpdate(insert);

    ResultSet result = statement.executeQuery("SELECT intset FROM t65 where key = 'key1';");

    // read the Set of Integer back out again
    Object rsObject = result.getObject(1);
    assertNotNull("Object Should Exist", rsObject);
    assertTrue("Object Should be Set", (rsObject instanceof Set));

    int sum = 0;

    // sum up the set - it should be 100
    for (Object rsEntry : ((Set) rsObject).toArray()) {
        assertTrue("Entry should be Integer", (rsEntry instanceof Integer));
        sum += ((Integer) rsEntry).intValue();
    }

    assertEquals("Total Should be 100", 100, sum);

    //System.out.println(resultToDisplay(result,65, "with set = {10,20,30,40}"));

    String update = "UPDATE t65 SET intset=? WHERE key=?;";

    PreparedStatement pstatement = con.prepareStatement(update);
    Set<Integer> mySet = new HashSet<Integer>();
    pstatement.setObject(1, mySet, Types.OTHER);
    pstatement.setString(2, "key1");

    pstatement.executeUpdate();

    result = statement.executeQuery("SELECT * FROM t65;");

    System.out.println(resultToDisplay(result, 65, " with set = <empty>"));

}

From source file:com.javaetmoi.elasticsearch.musicbrainz.batch.mapper.AlbumRowMapper.java

@Override
public Album mapRow(ResultSet rs, int rowNum) throws SQLException {
    Album album = new Album();
    album.setId(rs.getInt("albumId"));
    album.setGid(rs.getString("albumGid"));
    album.setName(rs.getString("albumName"));
    album.setTypeId(rs.getInt("albumPrimaryTypeId"));
    album.setTypeName(rs.getString("albumPrimaryTypeName"));
    album.setYear(rs.getInt("albumYear"));
    album.getRating().setScore(rs.getInt("albumRatingScore"));
    album.getRating().setCount(rs.getInt("albumRatingCount"));

    Artist artist = album.getArtist();/*  w  w  w. j  a  v a2s.c  o m*/
    artist.setGid(rs.getString("artistGid"));
    artist.setName(rs.getString("artistName"));
    artist.setBeginDateYear(rs.getString("artistBeginDateYear"));
    if (rs.getObject("artistTypeId") != null) {
        artist.setTypeId(rs.getInt("artistTypeId"));
    }
    if (rs.getObject("artistTypeName") != null) {
        artist.setTypeName(rs.getString("artistTypeName"));
    }
    if (rs.getObject("artistGenderId") != null) {
        artist.setGender(Gender.valueOf(rs.getInt("artistGenderId")));
    }
    artist.setArea(rs.getString("artistCountryName"));
    artist.getRating().setScore(rs.getInt("artistRatingScore"));
    artist.getRating().setCount(rs.getInt("artistRatingCount"));

    return album;
}

From source file:edu.ku.brc.specify.config.FixDBAfterLogin.java

/**
 * //from w  w w  .  j av  a2  s . co m
 */
public static void fixUserPermissions(final boolean doSilently) {
    final String FIXED_USER_PERMS = "FIXED_USER_PERMS";
    boolean isAlreadyFixed = AppPreferences.getRemote().getBoolean(FIXED_USER_PERMS, false);
    if (isAlreadyFixed) {
        return;
    }

    String whereStr = " WHERE p.GroupSubClass = 'edu.ku.brc.af.auth.specify.principal.UserPrincipal' ";
    String whereStr2 = "AND p.userGroupScopeID IS NULL";

    String postSQL = " FROM specifyuser su "
            + "INNER JOIN specifyuser_spprincipal ss ON su.SpecifyUserID = ss.SpecifyUserID "
            + "INNER JOIN spprincipal p ON ss.SpPrincipalID = p.SpPrincipalID "
            + "LEFT JOIN spprincipal_sppermission pp ON p.SpPrincipalID = pp.SpPrincipalID "
            + "LEFT OUTER JOIN sppermission pm ON pp.SpPermissionID = pm.SpPermissionID " + whereStr;

    String sql = "SELECT COUNT(*)" + postSQL + whereStr2;
    log.debug(sql);
    if (BasicSQLUtils.getCountAsInt(sql) < 1) {
        sql = "SELECT COUNT(*)" + postSQL;
        log.debug(sql);
        if (BasicSQLUtils.getCountAsInt(sql) > 0) {
            return;
        }
    }

    final String updatePermSQL = "DELETE FROM %s WHERE SpPermissionID = %d";
    final String updatePrinSQL = "DELETE FROM %s WHERE SpPrincipalID = %d";

    sql = "SELECT p.SpPrincipalID, pp.SpPermissionID" + postSQL;
    log.debug(sql);

    HashSet<Integer> prinIds = new HashSet<Integer>();
    for (Object[] row : query(sql)) {
        Integer prinId = (Integer) row[0];
        if (prinId != null) {
            prinIds.add(prinId);
        }

        Integer permId = (Integer) row[1];
        if (permId != null) {
            update(String.format(updatePermSQL, "spprincipal_sppermission", permId));
            update(String.format(updatePermSQL, "sppermission", permId));
            log.debug("Removing PermId: " + permId);
        }
    }

    StringBuilder sb1 = new StringBuilder();
    for (Integer prinId : prinIds) {
        update(String.format(updatePrinSQL, "specifyuser_spprincipal", prinId));
        update(String.format(updatePrinSQL, "spprincipal", prinId));
        log.debug("Removing PrinId: " + prinId);
        if (sb1.length() > 0)
            sb1.append(",");
        sb1.append(prinId.toString());
    }
    log.debug("(" + sb1.toString() + ")");

    // Create all the necessary UperPrincipal records
    // Start by figuring out what group there are and then create one UserPrincipal record
    // for each one

    TreeSet<String> nameSet = new TreeSet<String>();
    sql = "SELECT su.Name, su.SpecifyUserID, p.userGroupScopeID, p.SpPrincipalID FROM specifyuser su "
            + "INNER JOIN specifyuser_spprincipal sp ON su.SpecifyUserID = sp.SpecifyUserID "
            + "INNER JOIN spprincipal p ON sp.SpPrincipalID = p.SpPrincipalID "
            + "WHERE p.GroupSubClass = 'edu.ku.brc.af.auth.specify.principal.GroupPrincipal'";

    String fields = "TimestampCreated, TimestampModified, Version, GroupSubClass, groupType, Name, Priority, Remarks, userGroupScopeID, CreatedByAgentID, ModifiedByAgentID";
    String insertSQL = "INSERT INTO spprincipal (" + fields + ") VALUES(?,?,?,?,?,?,?,?,?,?,?)";
    String insertSQL2 = "INSERT INTO specifyuser_spprincipal (SpecifyUserID, SpPrincipalID) VALUES(?,?)";

    String searchSql = "SELECT " + fields + " FROM spprincipal WHERE SpPrincipalID = ?";

    sb1 = new StringBuilder();

    PreparedStatement selStmt = null;
    PreparedStatement pStmt = null;
    PreparedStatement pStmt2 = null;
    try {
        Connection conn = DBConnection.getInstance().getConnection();

        pStmt = conn.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
        pStmt2 = conn.prepareStatement(insertSQL2);
        selStmt = conn.prepareStatement(searchSql);

        String adtSQL = "SELECT DISTINCT ca.AgentID FROM specifyuser AS su INNER Join agent AS ca ON su.CreatedByAgentID = ca.AgentID";
        Integer createdById = BasicSQLUtils.getCount(conn, adtSQL);
        if (createdById == null) {
            createdById = BasicSQLUtils.getCount(conn,
                    "SELECT AgentID FROM agent ORDER BY AgentID ASC LIMIT 0,1");
            if (createdById == null) {
                UIRegistry.showError("The permissions could not be fixed because there were no agents.");
                AppPreferences.shutdownAllPrefs();
                DBConnection.shutdownFinalConnection(true, true);
                return;
            }
        }

        for (Object[] row : query(sql)) {
            String usrName = (String) row[0];
            Integer userId = (Integer) row[1];
            Integer collId = (Integer) row[2];
            Integer prinId = (Integer) row[3];

            nameSet.add(usrName);

            log.debug("usrName: " + usrName + "  prinId: " + prinId);
            if (sb1.length() > 0)
                sb1.append(",");
            sb1.append(prinId.toString());

            selStmt.setInt(1, prinId);
            ResultSet rs = selStmt.executeQuery();
            if (rs.next()) {
                log.debug(String.format("%s - adding UserPrincipal for Collection  %d / %d", usrName,
                        rs.getInt(9), collId));
                Integer createdByAgentID = (Integer) rs.getObject(10);
                Integer modifiedByAgentID = (Integer) rs.getObject(11);

                pStmt.setTimestamp(1, rs.getTimestamp(1));
                pStmt.setTimestamp(2, rs.getTimestamp(2));
                pStmt.setInt(3, 1); // Version
                pStmt.setString(4, "edu.ku.brc.af.auth.specify.principal.UserPrincipal"); // GroupSubClass
                pStmt.setString(5, null); // groupType
                pStmt.setString(6, rs.getString(6)); // Name
                pStmt.setInt(7, 80); // Priority
                pStmt.setString(8, rs.getString(8)); // Remarks
                pStmt.setInt(9, rs.getInt(9)); // userGroupScopeID
                pStmt.setInt(10, createdByAgentID != null ? createdByAgentID : createdById);
                pStmt.setInt(11, modifiedByAgentID != null ? modifiedByAgentID : createdById);

                // Create UserPrincipal
                pStmt.executeUpdate();

                int newPrinId = BasicSQLUtils.getInsertedId(pStmt);

                // Join the new Principal to the SpecifyUser record
                pStmt2.setInt(1, userId);
                pStmt2.setInt(2, newPrinId);
                pStmt2.executeUpdate();

            } else {
                // error
            }
            rs.close();
        }

        log.debug("(" + sb1.toString() + ")");

        AppPreferences.getRemote().putBoolean(FIXED_USER_PERMS, true);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (pStmt != null)
                pStmt.close();
            if (pStmt2 != null)
                pStmt2.close();
            if (selStmt != null)
                selStmt.close();
        } catch (Exception ex) {
        }
    }

    final StringBuilder sb = new StringBuilder();
    for (String nm : nameSet) {
        if (sb.length() > 0)
            sb.append('\n');
        sb.append(nm);
    }

    if (!doSilently) {
        JTextArea ta = UIHelper.createTextArea(15, 30);
        ta.setText(sb.toString());
        ta.setEditable(false);

        JEditorPane htmlPane = new JEditorPane("text/html", //$NON-NLS-1$
                UIRegistry.getResourceString("FDBAL_PERMFIXEDDESC"));
        htmlPane.setEditable(false);
        htmlPane.setOpaque(false);

        CellConstraints cc = new CellConstraints();
        PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p:g,8px,f:p:g"));
        pb.add(htmlPane, cc.xy(1, 1));
        pb.add(UIHelper.createScrollPane(ta), cc.xy(1, 3));
        pb.setDefaultDialogBorder();

        CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(),
                UIRegistry.getResourceString("FDBAL_PERMFIXED"), true, CustomDialog.OK_BTN, pb.getPanel());
        dlg.setOkLabel(UIRegistry.getResourceString("CLOSE"));
        UIHelper.centerAndShow(dlg);
    }
}

From source file:com.ws.WS_TCS201.java

@Path("/GetDETAIL/{com}/{account}")
@JSONP(queryParam = "callback")
@GET//from w ww .  j av  a 2  s  .  c  om
@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:net.pms.dlna.DLNAMediaDatabase.java

private Double toDouble(ResultSet rs, String column) throws SQLException {
    Object obj = rs.getObject(column);
    if (obj instanceof Double) {
        return (Double) obj;
    }//  ww w .  j a va  2  s  . co m
    return null;
}