Example usage for java.sql ResultSetMetaData getColumnType

List of usage examples for java.sql ResultSetMetaData getColumnType

Introduction

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

Prototype

int getColumnType(int column) throws SQLException;

Source Link

Document

Retrieves the designated column's SQL type.

Usage

From source file:edu.ku.brc.specify.conversion.ConvertTaxonHelper.java

/**
 * @param rs/*from www  .j a  v  a 2  s  .  c o  m*/
 * @param rsmd
 * @param parentNodeId
 * @return
 * @throws SQLException
 */
protected boolean processRow(final ResultSet rs, final ResultSetMetaData rsmd, final Integer parentNodeId)
        throws SQLException {
    for (int colInx = 1; colInx <= cols.length; colInx++) {
        pStmtTx.setNull(colInx, colTypes[colInx - 1]);
    }

    Boolean isRoot = null;
    boolean skip = false;
    for (int colInx = 1; colInx <= oldCols.length && !skip; colInx++) {
        String oldName = oldCols[colInx - 1];
        Integer newInx = fieldToColHash.get(oldName);
        if (newInx == null) {
            String newName = oldToNewColMap.get(oldName);
            if (newName != null) {
                newInx = fieldToColHash.get(newName);
                if (newInx == -1) {
                    String msg = "Couldn't find column index for New Name[" + newName + "]";
                    log.error(msg);
                    tblWriter.logError(msg);
                }
            } else if (colInx == lastEditedByInx) {
                String lastEditedByStr = rs.getString(colInx);
                if (StringUtils.isNotEmpty(lastEditedByStr)) {
                    Integer agtId = conversion.getModifiedByAgentId(lastEditedByStr);
                    if (agtId != null) {
                        pStmtTx.setInt(modifiedByAgentInx, agtId);
                        continue;
                    }
                }

                pStmtTx.setInt(colInx, conversion.getCurAgentModifierID());
                continue;

            } else if (colInx != 20) {
                String msg = "Couldn't find Old Name[" + oldName + "]";
                log.error(msg);
                tblWriter.logError(msg);
            } else {
                continue; // GroupToView
            }
        }

        if (colInx < 6) {
            if (isRoot == null) {
                isRoot = rs.getInt(rankIdOldDBInx) == 0;
            }
            Integer oldID = rs.getInt(colInx);
            if (!rs.wasNull() || (isRoot && colInx == 2)) {
                //     1                  2                 3               4                   5                     6                   7          
                //"TaxonNameID", "ParentTaxonNameID", "TaxonomyTypeID", "AcceptedID", "TaxonomicUnitTypeID", "TaxonomicSerialNumber", "TaxonName"
                boolean skipError = false;
                Integer newID = mappers[colInx - 1].get(oldID);
                if (newID == null) {
                    if (colInx == 3 || colInx == 5) // TaxonomyTypeID or TaxonomicUnitTypeID
                    {
                        if (!isRoot) {
                            skip = true;
                        }

                    } else if (colInx == 2 && (parentNodeId != null || isRoot)) // ParentTaxonNameID and is root
                    {
                        // Note for RankID == 0 the parent would be null because it is the root
                        newID = parentNodeId;

                    } else // OK Parent is NULL
                    {
                        boolean wasInOldTaxonTable = BasicSQLUtils.getCountAsInt(oldDBConn,
                                "SELECT COUNT(*) FROM taxonname WHERE TaxonNameID = " + oldID) > 0;
                        boolean isDetPointToTaxon = BasicSQLUtils.getCountAsInt(oldDBConn,
                                "SELECT COUNT(*) FROM determination WHERE TaxonNameID = " + oldID) > 0;
                        String msg = "&nbsp;";
                        if (isDetPointToTaxon) {
                            msg = String.format(
                                    "***** Couldn't get %s NewID [%d] from mapper for colInx[%d] In Old taxonname table: %s  WasParentID: %s  Det Using: %s",
                                    (colInx == 2 ? "Parent" : ""), oldID, colInx,
                                    (wasInOldTaxonTable ? "YES" : "no"), (colInx == 2 ? "YES" : "no"),
                                    (isDetPointToTaxon ? "YES" : "no"));
                            log.error(msg);
                            tblWriter.logError(msg);
                        }

                        skipError = true;
                        if (colInx == 2) {
                            Integer oldRecId = rs.getInt(1);
                            msg = String.format("Parent was NULL for OldID %d for Taxa %s", oldRecId,
                                    rs.getString(7));
                            missingParentList.add(new Pair<Integer, String>(oldRecId, msg));
                        }
                    }
                }

                if (!skip) {
                    if (newID != null) {
                        //System.out.println("newInx["+newInx+"]  newID["+newID+"] oldID["+oldID+"]");
                        pStmtTx.setInt(newInx, newID);

                    } else if (!skipError && !isRoot) {
                        String msg = "Unable to map old TaxonNameID[" + oldID + "]";
                        log.error(msg);
                        tblWriter.logError(msg);
                    }
                }
            } else {
                //log.error("***** Old ID Col ["+colInx+"] was null");
                //skip = true;
            }
            continue;
        }

        switch (colTypes[newInx - 1]) {
        case java.sql.Types.BIT: {
            boolean val = rs.getBoolean(colInx);
            if (!rs.wasNull())
                pStmtTx.setBoolean(newInx, val);
            break;
        }
        case java.sql.Types.INTEGER: {
            int val = rs.getInt(colInx);
            if (!rs.wasNull())
                pStmtTx.setInt(newInx, val);

            //System.out.println("newInx["+colInx+"]  newID["+val+"]");
            break;
        }
        case java.sql.Types.SMALLINT: {
            short val = rs.getShort(colInx);
            if (!rs.wasNull())
                pStmtTx.setShort(newInx, val);
            break;
        }
        case java.sql.Types.TIMESTAMP: {
            Timestamp val = rs.getTimestamp(colInx);
            //if (val == null && oldName.equals("Date"))
            //{
            //    pStmtTx.setTimestamp(newInx, null);
            //} else
            //{
            pStmtTx.setTimestamp(newInx, !rs.wasNull() ? val : null);
            //}
            break;
        }
        case java.sql.Types.LONGVARCHAR:
        case java.sql.Types.VARCHAR: {
            int len = colSizes[newInx - 1];
            String val = rs.getString(colInx);
            if (val != null && val.length() > len) {
                String newName = oldToNewColMap.get(oldName);
                String msg = String.format("Concatinating field [%s] from length %d to %d String Lost:[%s]",
                        newName, val.length(), len, val.substring(len));
                log.debug(msg);
                tblWriter.logError(msg);

                val = val.substring(0, len);
            }
            if (!rs.wasNull()) {
                pStmtTx.setString(newInx, val);

            } else if (colInx == 7) {
                pStmtTx.setString(newInx, "Empty");
            }
            break;
        }
        default:
            log.error("Didn't support SQL Type: " + rsmd.getColumnType(colInx));
            break;
        }

    }

    if (!skip) {
        if (parentNodeId != null) {
            int nxtId = BasicSQLUtils.getCountAsInt("SELECT TaxonID FROM taxon ORDER BY TaxonID DESC LIMIT 0,1")
                    + 1;
            pStmtTx.setInt(1, nxtId);
        }

        pStmtTx.setInt(fieldToColHash.get("Version"), 0);
        pStmtTx.setInt(fieldToColHash.get("IsHybrid"), 0); //IsHybrid can't be null. I think this fixes it.
        try {
            //System.out.println("----------------------------------------");
            pStmtTx.execute();

        } catch (Exception ex) {
            UIRegistry.showError(ex.toString());
        }
    }

    return true;
}

From source file:edu.ku.brc.specify.conversion.MSULichensFixer.java

/**
 * @param rs/*  www  .  j  av a 2  s .  c  o  m*/
 * @param rsmd
 * @param parentNodeId
 * @return
 * @throws SQLException
 */
protected boolean processRow(final ResultSet rs, final ResultSetMetaData rsmd, final Integer parentNodeId)
        throws SQLException {
    for (int colInx = 1; colInx <= cols.length; colInx++) {
        pStmtTx.setNull(colInx, colTypes[colInx - 1]);
    }

    String newName = null;
    Boolean isRoot = null;
    boolean skip = false;
    for (int colInx = 1; colInx <= oldCols.length && !skip; colInx++) {
        String oldName = oldCols[colInx - 1];
        Integer newInx = fieldToColHash.get(oldName);
        if (newInx == null) {
            newName = oldToNewColMap.get(oldName);
            if (newName != null) {
                newInx = fieldToColHash.get(newName);
                if (newInx == -1) {
                    String msg = "Couldn't find column index for New Name[" + newName + "]";
                    log.error(msg);
                    tblWriter.logError(msg);
                }
            } else if (colInx == lastEditedByInx) {
                String lastEditedByStr = rs.getString(colInx);
                if (StringUtils.isNotEmpty(lastEditedByStr)) {
                    Integer agtId = 1;//conversion.getModifiedByAgentId(lastEditedByStr);
                    if (agtId != null) {
                        pStmtTx.setInt(modifiedByAgentInx, agtId);
                        continue;
                    }
                }

                pStmtTx.setInt(colInx, 1);
                continue;

            } else if (colInx != 20) {
                String msg = "Couldn't find Old Name[" + oldName + "]";
                log.error(msg);
                tblWriter.logError(msg);
            } else {
                continue; // GroupToView
            }
        }

        if (colInx < 6) {
            if (isRoot == null) {
                isRoot = rs.getInt(rankIdOldDBInx) == 0;
            }
            Integer oldID = rs.getInt(colInx);
            if (!rs.wasNull() || (isRoot && colInx == 2)) {
                boolean skipError = false;

                Integer newID = null;
                if (oldID == 612195491)
                    oldID = 21;
                else if (oldID == -447245554)
                    oldID = -1414322196;

                if (oldName.equals("TaxonomyTypeID")) {
                    newID = 1;

                } else if (oldName.equals("TaxonomicUnitTypeID")) {
                    String s = "SELECT RankID FROM taxonomicunittype WHERE TaxonomicUnitTypeID = " + oldID;
                    Integer rankId = BasicSQLUtils.getCount(oldDBConn, s);
                    log.debug(s);
                    switch (rankId) {
                    case 0:
                        newID = 8;
                        break;
                    case 10:
                        newID = 12;
                        break;
                    case 20:
                        newID = 22;
                        break;
                    case 30:
                        newID = 23;
                        break;
                    case 40:
                        newID = 7;
                        break;
                    case 60:
                        newID = 14;
                        break;
                    case 70:
                        newID = 4;
                        break;
                    case 100:
                        newID = 17;
                        break;
                    case 110:
                        newID = 19;
                        break;
                    case 140:
                        newID = 15;
                        break;
                    case 150:
                        newID = 10;
                        break;
                    case 160:
                        newID = 16;
                        break;
                    case 170:
                        newID = 2;
                        break;
                    case 180:
                        newID = 5;
                        break;
                    case 190:
                        newID = 13;
                        break;
                    case 200:
                        newID = 1;
                        break;
                    case 210:
                        newID = 6;
                        break;
                    case 220:
                        newID = 21;
                        break;
                    case 230:
                        newID = 18;
                        break;
                    case 240:
                        newID = 11;
                        break;
                    case 250:
                        newID = 3;
                        break;
                    case 260:
                        newID = 20;
                        break;
                    case 270:
                        newID = 9;
                        break;
                    default:
                        log.error("Error with rank: " + rankId);
                    }

                } else {
                    newID = mappers[colInx - 1].get(oldID);
                    if (newID == null && (colInx == 5 || colInx == 3)) {
                        String s = "SELECT RankID FROM taxonomicunittype WHERE TaxonomicUnitTypeID = " + oldID;
                        Integer rankId = BasicSQLUtils.getCount(oldDBConn, s);
                        log.debug(s);
                        if (rankId != null) {
                            s = "SELECT TaxonomicUnitTypeID FROM taxonomicunittype WHERE TaxonomyTypeID = 6 && RankID = "
                                    + rankId;
                            oldID = BasicSQLUtils.getCount(oldDBConn, s);
                            log.debug(s);
                            if (oldID != null) {
                                newID = mappers[colInx - 1].get(oldID);
                                if (newID == null) {
                                    log.error("newID is null for Old Id " + oldID + "   colInx: " + colInx);
                                }
                            } else {
                                log.error("oldID is null");
                            }
                        } else {
                            log.error("rankId is null");
                        }
                    }

                }

                if (newID == null) {
                    if (colInx == 3 || colInx == 5) {
                        if (!isRoot) {
                            skip = true;
                        }

                    } else if (colInx == 2 && (parentNodeId != null || isRoot)) {
                        // Note for RankID == 0 the parent would be null because it is the root
                        newID = parentNodeId;

                    } else {
                        boolean wasInOldTaxonTable = BasicSQLUtils.getCountAsInt(oldDBConn,
                                "SELECT COUNT(*) FROM taxonname WHERE TaxonNameID = " + oldID) > 0;
                        boolean isDetPointToTaxon = BasicSQLUtils.getCountAsInt(oldDBConn,
                                "SELECT COUNT(*) FROM determination WHERE TaxonNameID = " + oldID) > 0;
                        if (isDetPointToTaxon) {
                            String msg = String.format(
                                    "***** Couldn't get %s NewID [%d] from mapper for colInx[%d] In Old taxonname table: %s  WasParentID: %s  Det Using: %s",
                                    (colInx == 2 ? "Parent" : ""), oldID, colInx,
                                    (wasInOldTaxonTable ? "YES" : "no"), (colInx == 2 ? "YES" : "no"),
                                    (isDetPointToTaxon ? "YES" : "no"));
                            log.error(msg);
                            tblWriter.logError(msg);
                        }
                        skipError = true;
                        missingParentTaxonCount++;
                    }
                }

                if (!skip) {
                    if (newID != null) {
                        //System.out.println("newInx["+newInx+"]  newID["+newID+"] oldID["+oldID+"]");
                        pStmtTx.setInt(newInx, newID);

                    } else if (!skipError && !isRoot) {
                        String msg = "Unable to map old TaxonNameID[" + oldID + "]";
                        log.error(msg);
                        tblWriter.logError(msg);
                    }
                }
            } else {
                //log.error("***** Old ID Col ["+colInx+"] was null");
                //skip = true;
            }
            continue;
        }

        switch (colTypes[newInx - 1]) {
        case java.sql.Types.BIT: {
            boolean val = rs.getBoolean(colInx);
            if (!rs.wasNull())
                pStmtTx.setBoolean(newInx, val);
            break;
        }
        case java.sql.Types.INTEGER: {
            int val = rs.getInt(colInx);
            if (!rs.wasNull())
                pStmtTx.setInt(newInx, val);

            //System.out.println("newInx["+colInx+"]  newID["+val+"]");
            break;
        }
        case java.sql.Types.SMALLINT: {
            short val = rs.getShort(colInx);
            if (!rs.wasNull())
                pStmtTx.setShort(newInx, val);
            break;
        }
        case java.sql.Types.TIMESTAMP: {
            Timestamp val = rs.getTimestamp(colInx);
            //if (val == null && oldName.equals("Date"))
            //{
            //    pStmtTx.setTimestamp(newInx, null);
            //} else
            //{
            pStmtTx.setTimestamp(newInx, !rs.wasNull() ? val : null);
            //}
            break;
        }
        case java.sql.Types.LONGVARCHAR:
        case java.sql.Types.VARCHAR: {
            int len = colSizes[newInx - 1];
            String val = rs.getString(colInx);
            if (val != null && val.length() > len) {
                newName = oldToNewColMap.get(oldName);
                String msg = String.format("Concatinating field [%s] from length %d to %d String Lost:[%s]",
                        newName, val.length(), len, val.substring(len));
                log.debug(msg);
                tblWriter.logError(msg);

                val = val.substring(0, len);
            }
            if (!rs.wasNull()) {
                pStmtTx.setString(newInx, val);

            } else if (colInx == 7) {
                pStmtTx.setString(newInx, "Empty");
            }
            break;
        }
        default:
            log.error("Didn't support SQL Type: " + rsmd.getColumnType(colInx));
            break;
        }

    }

    if (!skip) {
        if (parentNodeId != null) {
            int nxtId = BasicSQLUtils.getCountAsInt("SELECT TaxonID FROM taxon ORDER BY TaxonID DESC LIMIT 0,1")
                    + 1;
            pStmtTx.setInt(1, nxtId);
        }

        pStmtTx.setInt(fieldToColHash.get("Version"), 0);
        try {
            //System.out.println("----------------------------------------");
            pStmtTx.execute();

        } catch (Exception ex) {
            ex.printStackTrace();
            UIRegistry.showError(ex.toString());
        }
    }

    return true;
}

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Populates model with the query results. The query executed is the
 * currently selected query in the combo-box.
 * /*from   www.  j av  a 2  s .  co  m*/
 * @param rawSqlStatement
 *          The SQL statement to execute
 * @param model
 *          The model to populate with the results
 * @param tripleFile
 *          The location to write the results to as triples.
 */
private void execute(String rawSqlStatement, ListTableModel<Object> model, File tripleFile) {
    String sqlStatement = rawSqlStatement;
    Statement stmt = null;
    ResultSet result = null;
    ResultSetMetaData meta = null;
    List<Object> rowData = null;
    int retValue = 0;
    SQLWarning warning = null;
    int[] myType;
    Object value;
    String typeName;
    String colName;
    String metaName;
    boolean hasResults = false;
    boolean hasBLOB = false;
    Date connAsk = null;
    Date connGot = null;
    Date stmtGot = null;
    Date queryStart = null;
    Date queryReady = null;
    Date queryRSFetched = null;
    Date queryRSProcessed = null;
    long rows = 0;
    int cols = 0;
    boolean hasParams = false;
    final List<StatementParameter> allParams = new ArrayList<StatementParameter>();
    List<Object> outParams = null;

    modeOfCurrentTable = whichModeValue();
    mapOfCurrentTables = new HashMap<String, String>();

    // Try to prevent incorrect selection of query type by checking
    // beginning of SQL statement for obvious stuff
    // First check "Select" and Describe query types
    if (!isOkayQueryType(getQuery().getSql())) {
        // If the query type is wrong, and the user doesn't override then
        // Get Out Of Here!
        return;
    }

    // If there were BLOB columns included in the last query the connection
    // will have been left open. Since we are executing a new query we
    // can close that old connection now.
    if (conn != null) {
        try {
            conn.close();
        } catch (Throwable any) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Error (expected) closing connection", any);
            }
        }
    }

    conn = null;

    try {
        messageOut(Resources.getString("msgExecuteQuery",
                asQuery.isSelected() ? Resources.getString("msgQuery")
                        : asDescribe.isSelected() ? Resources.getString("msgDescribe")
                                : Resources.getString("msgUpdate"),
                sqlStatement), STYLE_BOLD);
        if (poolConnect.isSelected()) {
            messageOut(Resources.getString("msgPoolStats") + " ", STYLE_SUBTLE, false);
            if (getDBPool() != null) {
                messageOut(Resources.getString("msgPoolStatsCount", getDBPool().getNumActive() + "",
                        getDBPool().getNumIdle() + ""));
                LOGGER.debug("Retrieved existing DB connection pool");
            } else {
                LOGGER.debug("No existing DB pool");
                messageOut(Resources.getString("msgPoolNone"));
            }
        }
        if (getDBPool() == null || /* conn == null */
                !((String) connectString.getEditor().getItem()).equals(lastConnection)
                || !userId.getText().equals(lastUserId)
                || !new String(password.getPassword()).equals(lastPassword)) {

            removeDBPool();

            lastConnection = (String) connectString.getEditor().getItem();
            lastUserId = userId.getText();
            lastPassword = new String(password.getPassword());

            if (poolConnect.isSelected()) {
                setupDBPool(lastConnection, lastUserId, lastPassword);
            }

            messageOut(Resources.getString("msgConnCreated", lastConnection, lastUserId), STYLE_SUBTLE);
        }
        connAsk = new java.util.Date();
        if (poolConnect.isSelected()) {
            conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + DBPOOL_NAME);
            LOGGER.debug("Got pooled connection");
            messageOut(Resources.getString("msgGotPoolConn"), STYLE_GREEN);
        } else {
            conn = DriverManager.getConnection(lastConnection, lastUserId, lastPassword);
            LOGGER.debug("Got non-pooled connection");
            messageOut(Resources.getString("msgGotDirectConn"), STYLE_GREEN);
        }

        if (hasParams = sqlStatement.indexOf("$PARAM[") > -1) {
            sqlStatement = makeParams(sqlStatement, allParams);
        }

        connGot = new java.util.Date();

        conn.setAutoCommit(autoCommit.isSelected());
        conn.setReadOnly(readOnly.isSelected());

        if (!hasParams) {
            stmt = conn.createStatement();
        } else {
            stmt = conn.prepareCall(sqlStatement);
            setupCall((CallableStatement) stmt, allParams);
        }

        stmtGot = new java.util.Date();

        try {
            if (!maxRows.getSelectedItem().equals(Resources.getString("proNoLimit"))) {
                stmt.setMaxRows(Integer.parseInt((String) maxRows.getSelectedItem()));
                messageOut("\n" + Resources.getString("msgMaxRows", stmt.getMaxRows() + ""), STYLE_SUBTLE);
            }
        } catch (Exception any) {
            LOGGER.warn("Unable to set maximum rows", any);
            messageOut(Resources.getString("errFailSetMaxRows", (String) maxRows.getSelectedItem(),
                    any.getMessage()), STYLE_YELLOW);
        }

        if (asQuery.isSelected() || asDescribe.isSelected()) {
            queryStart = new java.util.Date();
            if (!hasParams) {
                int updateCount;

                // Execute the query synchronously
                stmt.execute(sqlStatement);
                messageOut(Resources.getString("msgQueryExecutedByDB"), STYLE_GREEN);

                // Process the query results and/or report status
                if ((updateCount = stmt.getUpdateCount()) > -1) {
                    do {
                        LOGGER.debug("Looking for results [update=" + updateCount + "]");
                        stmt.getMoreResults();
                    } while ((updateCount = stmt.getUpdateCount()) > -1);
                }
                result = stmt.getResultSet();
            } else {
                result = ((PreparedStatement) stmt).executeQuery();
            }
            queryReady = new java.util.Date();
            meta = result.getMetaData();
            cols = meta.getColumnCount();
        } else {
            queryStart = new java.util.Date();
            if (!hasParams) {
                retValue = stmt.executeUpdate(sqlStatement);
            } else {
                retValue = ((PreparedStatement) stmt).executeUpdate();
            }
            queryReady = new java.util.Date();
        }

        if (asQuery.isSelected()) {
            for (int col = 0; col < cols; ++col) {
                colName = meta.getColumnName(col + 1);
                if (colName == null || colName.trim().length() == 0) {
                    colName = Resources.getString("msgUnnamedColumn", meta.getColumnLabel(col + 1));
                }

                if (configDisplayColumnDataType.isSelected()) {
                    metaName = meta.getColumnTypeName(col + 1) + " " + meta.getColumnDisplaySize(col + 1)
                            + " (";

                    // have had oracle tables report large precision values
                    // for BLOB fields that caused exception to be thrown
                    // by getPrecision() since the value was beyond int
                    try {
                        metaName += meta.getPrecision(col + 1);
                    } catch (Exception any) {
                        metaName += "?";
                        LOGGER.warn("Unable to get column precision", any);
                    }
                    metaName += ".";
                    metaName += meta.getScale(col + 1);
                    metaName += ")";

                    colName += " [" + metaName + "]";
                }

                model.addColumn(colName);
                // Keep collection of tables used for Insert and Update Menu
                // Selections
                try {
                    mapOfCurrentTables.put(meta.getTableName(col + 1), null);
                } catch (Exception any) {
                    // Probably unimplemented method - Sybase driver
                    LOGGER.warn("Failed to obtain table name from metadata", any);
                    messageOut(Resources.getString("errFailReqTableName", any.getMessage()), STYLE_SUBTLE);
                }
            }

            rowData = new ArrayList<Object>();

            myType = new int[cols];

            for (int col = 0; col < cols; ++col) {
                typeName = meta.getColumnTypeName(col + 1).toUpperCase();
                if (typeName.equals("NUMBER")) {
                    if (meta.getScale(col + 1) > 0) {
                        myType[col] = COLUMN_DATA_TYPE_DOUBLE; // DOUBLE
                    } else if (meta.getPrecision(col + 1) <= MAX_DIGITS_FOR_INT) {
                        myType[col] = COLUMN_DATA_TYPE_INT; // INTEGER
                    } else {
                        myType[col] = COLUMN_DATA_TYPE_LONG; // LONG
                    }
                } else if (typeName.equals("LONG")) {
                    myType[col] = COLUMN_DATA_TYPE_LONG;
                } else if (typeName.equals("DATETIME")) {
                    myType[col] = COLUMN_DATA_TYPE_DATETIME; // Date/Time
                } else if (typeName.equals("DATE")) {
                    myType[col] = COLUMN_DATA_TYPE_DATE; // Date/Time
                } else if (typeName.equals("BLOB")) {
                    myType[col] = COLUMN_DATA_TYPE_BLOB;
                    hasBLOB = true;
                } else {
                    myType[col] = 0; // Default - String
                }
            }

            if (tripleFile != null) {
                try {
                    final RdbToRdf exporter = new RdbToRdf(tripleFile.getAbsolutePath(), getQuery().getSql(),
                            result);
                    exporter.run();
                    rows = exporter.getLatestNumberOfRowsExported();
                    messageOut("");
                    messageOut(Resources.getString("msgEndExportToFile"), STYLE_BOLD);
                } catch (Throwable throwable) {
                    messageOut(Resources.getString("errFailDataSave", throwable.toString()), STYLE_RED);
                    LOGGER.error("Failed to save data to triples file: " + tripleFile.getAbsolutePath(),
                            throwable);
                }
            } else if (fileLogResults.isSelected()) {
                writeDataAsCSV(sqlStatement, model, DBRESULTS_NAME, result, myType, false);
            } else {
                while (result.next()) {
                    ++rows;
                    rowData = new ArrayList<Object>();

                    for (int col = 0; col < cols; ++col) {
                        value = getResultField(result, col + 1, myType[col]);
                        rowData.add(value);
                    }

                    model.addRowFast(rowData);
                    hasResults = true;
                }
                model.updateCompleted();
            }

            queryRSProcessed = new java.util.Date();
        } else if (asDescribe.isSelected()) {
            String colLabel;

            meta = result.getMetaData();

            myType = new int[DESC_TABLE_COLUMN_COUNT];

            for (int col = 0; col < DESC_TABLE_COLUMN_COUNT; ++col) {
                switch (col) {
                case DESC_TABLE_NAME_COLUMN: // Col Name
                    colLabel = Resources.getString("proColumnName");
                    myType[col] = COLUMN_DATA_TYPE_STRING;
                    break;
                case DESC_TABLE_TYPE_COLUMN: // Col Type
                    colLabel = Resources.getString("proColumnType");
                    myType[col] = COLUMN_DATA_TYPE_STRING;
                    break;
                case DESC_TABLE_LENGTH_COLUMN: // Col Length
                    colLabel = Resources.getString("proColumnLength");
                    myType[col] = COLUMN_DATA_TYPE_INT;
                    break;
                case DESC_TABLE_PRECISION_COLUMN: // Col precision
                    colLabel = Resources.getString("proColPrecision");
                    myType[col] = COLUMN_DATA_TYPE_INT;
                    break;
                case DESC_TABLE_SCALE_COLUMN: // Col scale
                    colLabel = Resources.getString("proColScale");
                    myType[col] = COLUMN_DATA_TYPE_INT;
                    break;
                case DESC_TABLE_NULLS_OK_COLUMN: // Nulls Okay?
                    colLabel = Resources.getString("proColNullsAllowed");
                    myType[col] = COLUMN_DATA_TYPE_STRING;
                    break;
                default: // oops
                    colLabel = Resources.getString("proColUndefined");
                    break;
                }

                if (configDisplayColumnDataType.isSelected()) {
                    colLabel += " [";
                    colLabel += myType[col] == 0 ? Resources.getString("proColCharType")
                            : Resources.getString("proColNumeric");
                    colLabel += "]";
                }

                model.addColumn(colLabel);
            }

            rowData = new ArrayList<Object>();

            for (int col = 0; col < cols; ++col) {
                rowData = new ArrayList<Object>();

                for (int row = 0; row < DESC_TABLE_COLUMN_COUNT; ++row) {
                    switch (row) {
                    case DESC_TABLE_NAME_COLUMN: // Name
                        colName = meta.getColumnName(col + 1);
                        if (colName == null || colName.trim().length() == 0) {
                            colName = Resources.getString("msgUnnamedColumn", meta.getColumnLabel(col + 1));
                        }
                        value = colName;
                        break;
                    case DESC_TABLE_TYPE_COLUMN: // Type
                        value = meta.getColumnTypeName(col + 1) + " (" + meta.getColumnType(col + 1) + ")";
                        break;
                    case DESC_TABLE_LENGTH_COLUMN: // Length
                        value = new Integer(meta.getColumnDisplaySize(col + 1));
                        break;
                    case DESC_TABLE_PRECISION_COLUMN: // Precision
                        try {
                            value = new Integer(meta.getPrecision(col + 1));
                        } catch (Exception any) {
                            value = "?";
                            LOGGER.warn("Unable to obtain column precision", any);
                        }
                        break;
                    case DESC_TABLE_SCALE_COLUMN: // Scale
                        value = new Integer(meta.getScale(col + 1));
                        break;
                    case DESC_TABLE_NULLS_OK_COLUMN: // Nulls Okay?
                        value = meta.isNullable(col + 1) == ResultSetMetaData.columnNullable
                                ? Resources.getString("proYes")
                                : meta.isNullable(col + 1) == ResultSetMetaData.columnNoNulls
                                        ? Resources.getString("proNo")
                                        : Resources.getString("proUnknown");
                        break;
                    default:
                        value = null;
                        break;
                    }

                    rowData.add(value);

                    // Keep collection of tables used for Insert and Update Menu
                    // Selections
                    try {
                        mapOfCurrentTables.put(meta.getTableName(col + 1), null);
                    } catch (Exception any) {
                        // Probably unimplemented method - Sybase driver
                        LOGGER.warn("Failed to obtain table name from metadata", any);
                        messageOut(Resources.getString("errFailReqTableName", any.getMessage()), STYLE_SUBTLE);
                    }
                }
                model.addRow(rowData);
            }

            while (result.next()) {
                rows++;
                for (int col = 0; col < cols; ++col) {
                    result.getObject(col + 1);
                }
            }

            queryRSFetched = new java.util.Date();

        } else {
            messageOut("\n" + Resources.getString("msgReturnValue") + " " + retValue, STYLE_BOLD, false);
            rows = stmt.getUpdateCount();
        }

        messageOut("\n" + Resources.getString("msgRows") + " ", STYLE_NORMAL, false);
        if (rows == stmt.getMaxRows() && rows > 0) {
            messageOut("" + rows, STYLE_YELLOW);
        } else {
            messageOut("" + rows, STYLE_BOLD);
        }
        messageOut("");
    } catch (SQLException sql) {
        LOGGER.error("Error executing SQL", sql);
        messageOut(Resources.getString("errFailSQL", sql.getClass().getName(), sql.getMessage()), STYLE_RED);
        userMessage(Resources.getString("errFailSQLText", sql.getMessage()),
                Resources.getString("errFailSQLTitle"), JOptionPane.ERROR_MESSAGE);
        while ((sql = sql.getNextException()) != null) {
            LOGGER.error("Next Exception", sql);
        }
        modeOfCurrentTable = -1;
    } catch (Throwable any) {
        LOGGER.error("Error executing SQL", any);
        messageOut(Resources.getString("errFailSQL", any.getClass().getName(), any.getMessage()), STYLE_RED);
        userMessage(Resources.getString("errFailSQLText", any.getMessage()),
                Resources.getString("errFailSQLTitle"), JOptionPane.ERROR_MESSAGE);
        modeOfCurrentTable = -1;
    } finally {
        fileSaveBLOBs.setEnabled(hasBLOB);
        setExportAvailable((hasResults && model.getRowCount() > 0) || tripleFile != null);
        queryMakeInsert.setEnabled(
                modeOfCurrentTable == Query.MODE_DESCRIBE || modeOfCurrentTable == Query.MODE_QUERY);

        if (hasParams) {
            outParams = getOutParams((CallableStatement) stmt, allParams);
        }

        LOGGER.debug("Check for more results");

        try {
            int resultCount = 0;
            while (stmt.getMoreResults()) {
                int updateCount;
                ++resultCount;
                updateCount = stmt.getUpdateCount();
                LOGGER.debug("More results [" + resultCount + "][updateCount=" + updateCount + "]");
            }
        } catch (SQLException sql) {
            LOGGER.error("Failed checking for more results", sql);
            messageOut(Resources.getString("errFailAddlResults", sql.getClass().getName(), sql.getMessage()));
        }

        LOGGER.debug("No more results");

        if (result != null) {
            try {
                result.close();
                LOGGER.info("Resultset closed");
            } catch (Throwable any) {
                LOGGER.error("Unable to close resultset", any);
            }
        }

        if (stmt != null) {
            try {
                warning = stmt.getWarnings();
                while (warning != null) {
                    LOGGER.warn("Stmt Warning: " + warning.toString());
                    messageOut(Resources.getString("errStmtWarning", warning.toString()), STYLE_YELLOW);
                    warning = warning.getNextWarning();
                }
            } catch (Throwable any) {
                LOGGER.warn("Error retrieving statement SQL warnings", any);
            }

            try {
                stmt.close();
                LOGGER.debug("Statement closed");
            } catch (Throwable any) {
                LOGGER.error("Unable to close statement", any);
            }
        }

        if (conn != null) {
            try {
                warning = conn.getWarnings();
                while (warning != null) {
                    LOGGER.warn("Connt Warning: " + warning.toString());
                    messageOut(Resources.getString("errConnWarning", warning.toString()), STYLE_YELLOW);
                    warning = warning.getNextWarning();
                }
            } catch (Throwable any) {
                LOGGER.warn("Error retrieving connection SQL warnings", any);
            }
        }

        // Close the connection if there are no BLOBs.
        // If the user decides to save a BLOB we will need to DB connection
        // to remain open, hence we only close here if there are no BLOBs
        if (!hasBLOB && conn != null) {
            try {
                conn.close();
                conn = null;
                LOGGER.debug("DB Connection closed");
            } catch (Throwable any) {
                LOGGER.error("Unable to close DB connection", any);
            }
        }

        reportStats(sqlStatement, connAsk, connGot, stmtGot, queryStart, queryReady, queryRSFetched,
                queryRSProcessed, rows, cols, asDescribe.isSelected() ? model : null, outParams);
        // reportResults(SQL, model);
    }
}