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:org.cloudgraph.rdb.filter.RDBStatementExecutor.java

@Override
public List<List<PropertyPair>> fetch(PlasmaType type, StringBuilder sql, Set<Property> props,
        Object[] params) {//from w  w w  .j av  a  2  s  .  co m
    List<List<PropertyPair>> result = new ArrayList<List<PropertyPair>>();
    PreparedStatement statement = null;
    ResultSet rs = null;
    try {
        if (log.isDebugEnabled()) {
            if (params == null || params.length == 0) {
                log.debug("fetch: " + sql.toString());
            } else {
                StringBuilder paramBuf = new StringBuilder();
                paramBuf.append(" [");
                for (int p = 0; p < params.length; p++) {
                    if (p > 0)
                        paramBuf.append(", ");
                    paramBuf.append(String.valueOf(params[p]));
                }
                paramBuf.append("]");
                log.debug("fetch: " + sql.toString() + " " + paramBuf.toString());
            }
        }
        statement = con.prepareStatement(sql.toString(), ResultSet.TYPE_FORWARD_ONLY, /*
                                                                                       * ResultSet
                                                                                       * .
                                                                                       * TYPE_SCROLL_INSENSITIVE
                                                                                       * ,
                                                                                       */
                ResultSet.CONCUR_READ_ONLY);

        for (int i = 0; i < params.length; i++)
            statement.setString(i + 1, // FIXME
                    String.valueOf(params[i]));

        statement.execute();
        rs = statement.getResultSet();
        ResultSetMetaData rsMeta = rs.getMetaData();
        int numcols = rsMeta.getColumnCount();

        int count = 0;
        while (rs.next()) {
            List<PropertyPair> row = new ArrayList<PropertyPair>(numcols);
            result.add(row);
            for (int i = 1; i <= numcols; i++) {
                String columnName = rsMeta.getColumnName(i);
                int columnType = rsMeta.getColumnType(i);
                PlasmaProperty prop = (PlasmaProperty) type.getProperty(columnName);
                PlasmaProperty valueProp = prop;
                while (!valueProp.getType().isDataType()) {
                    valueProp = this.statementUtil.getOppositePriKeyProperty(valueProp);
                }
                Object value = converter.fromJDBCDataType(rs, i, columnType, valueProp);
                if (value != null) {
                    PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value);
                    if (!valueProp.equals(prop))
                        pair.setValueProp(valueProp);
                    if (!props.contains(prop))
                        pair.setQueryProperty(false);
                    row.add(pair);
                }
            }
            count++;
        }
        if (log.isDebugEnabled())
            log.debug("returned " + count + " results");
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
    return result;
}

From source file:org.apache.sqoop.manager.SqlManager.java

/**
 * Get column types for a query statement that we do not modify further.
 *//*  w  w w  . ja  va2 s . co  m*/
protected Map<String, Integer> getColumnTypesForRawQuery(String stmt) {
    ResultSet results;
    try {
        results = execute(stmt);
    } catch (SQLException sqlE) {
        LOG.error("Error executing statement: " + sqlE.toString(), sqlE);
        release();
        return null;
    }

    try {
        Map<String, Integer> colTypes = new SqlTypeMap<String, Integer>();

        int cols = results.getMetaData().getColumnCount();
        ResultSetMetaData metadata = results.getMetaData();
        for (int i = 1; i < cols + 1; i++) {
            int typeId = metadata.getColumnType(i);
            // If we have an unsigned int we need to make extra room by
            // plopping it into a bigint
            if (typeId == Types.INTEGER && !metadata.isSigned(i)) {
                typeId = Types.BIGINT;
            }

            String colName = metadata.getColumnName(i);
            if (colName == null || colName.equals("")) {
                colName = metadata.getColumnLabel(i);
            }

            colTypes.put(colName, Integer.valueOf(typeId));
        }

        return colTypes;
    } catch (SQLException sqlException) {
        LOG.error("Error reading from database: " + sqlException.toString());
        return null;
    } finally {
        try {
            results.close();
            getConnection().commit();
        } catch (SQLException sqlE) {
            LOG.warn("SQLException closing ResultSet: " + sqlE.toString());
        }

        release();
    }
}

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.//www  . j  a v a2s . c o m
 *
 * 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:org.sakaiproject.webservices.SakaiReport.java

protected Document toDocument(ResultSet rs) throws ParserConfigurationException, SQLException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element results = doc.createElement("Results");
    doc.appendChild(results);//from ww w.  ja  v  a2  s. com

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);

        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnLabel(i);
            Object value = null;
            try {
                value = getColumnValue(rs, rsmd.getColumnType(i), i);
                Element node = doc.createElement(columnName);
                node.appendChild(doc.createTextNode(stripInvalidXmlCharacters(value.toString())));
                row.appendChild(node);
            } catch (IOException e) {
                // probably shouldn't just ignore an issue...
                e.printStackTrace();
            }

        }
    }
    return doc;
}

From source file:org.sakaiproject.webservices.SakaiReport.java

protected String toJsonString(ResultSet rs) throws SQLException, JSONException {
    ResultSetMetaData rsmd = rs.getMetaData();
    JSONArray array = new JSONArray();
    int numColumns = rsmd.getColumnCount();

    while (rs.next()) {

        JSONObject obj = new JSONObject();
        for (int i = 1; i < numColumns + 1; i++) {

            String column_label = rsmd.getColumnLabel(i);

            LOG.debug("Column Name=" + column_label + ",type=" + rsmd.getColumnType(i));

            switch (rsmd.getColumnType(i)) {
            case Types.ARRAY:
                obj.put(column_label, rs.getArray(i));
                break;
            case Types.BIGINT:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.BOOLEAN:
                obj.put(column_label, rs.getBoolean(i));
                break;
            case Types.BLOB:
                obj.put(column_label, rs.getBlob(i));
                break;
            case Types.DOUBLE:
                obj.put(column_label, rs.getDouble(i));
                break;
            case Types.FLOAT:
                obj.put(column_label, rs.getFloat(i));
                break;
            case Types.INTEGER:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.NVARCHAR:
                obj.put(column_label, rs.getNString(i));
                break;
            case Types.VARCHAR:
                obj.put(column_label, rs.getString(i));
                break;
            case Types.TINYINT:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.SMALLINT:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.DATE:
                obj.put(column_label, rs.getDate(i));
                break;
            case Types.TIMESTAMP:
                obj.put(column_label, rs.getTimestamp(i));
                break;
            default:
                obj.put(column_label, rs.getObject(i));
                break;
            }/*  w  ww.  j av  a  2s .  com*/

        }
        array.put(obj);

    }
    return array.toString();
}

From source file:org.apache.nifi.util.hive.HiveJdbcCommon.java

public static long convertToCsvStream(final ResultSet rs, final OutputStream outStream, String recordName,
        ResultSetRowCallback callback, CsvOutputOptions outputOptions) throws SQLException, IOException {

    final ResultSetMetaData meta = rs.getMetaData();
    final int nrOfColumns = meta.getColumnCount();
    List<String> columnNames = new ArrayList<>(nrOfColumns);

    if (outputOptions.isHeader()) {
        if (outputOptions.getAltHeader() == null) {
            for (int i = 1; i <= nrOfColumns; i++) {
                String columnNameFromMeta = meta.getColumnName(i);
                // Hive returns table.column for column name. Grab the column name as the string after the last period
                int columnNameDelimiter = columnNameFromMeta.lastIndexOf(".");
                columnNames.add(columnNameFromMeta.substring(columnNameDelimiter + 1));
            }/*from  w w w  .j av  a  2  s  .co m*/
        } else {
            String[] altHeaderNames = outputOptions.getAltHeader().split(",");
            columnNames = Arrays.asList(altHeaderNames);
        }
    }

    // Write column names as header row
    outStream.write(
            StringUtils.join(columnNames, outputOptions.getDelimiter()).getBytes(StandardCharsets.UTF_8));
    if (outputOptions.isHeader()) {
        outStream.write("\n".getBytes(StandardCharsets.UTF_8));
    }

    // Iterate over the rows
    long nrOfRows = 0;
    while (rs.next()) {
        if (callback != null) {
            callback.processRow(rs);
        }
        List<String> rowValues = new ArrayList<>(nrOfColumns);
        for (int i = 1; i <= nrOfColumns; i++) {
            final int javaSqlType = meta.getColumnType(i);
            final Object value = rs.getObject(i);

            switch (javaSqlType) {
            case CHAR:
            case LONGNVARCHAR:
            case LONGVARCHAR:
            case NCHAR:
            case NVARCHAR:
            case VARCHAR:
                String valueString = rs.getString(i);
                if (valueString != null) {
                    // Removed extra quotes as those are a part of the escapeCsv when required.
                    StringBuilder sb = new StringBuilder();
                    if (outputOptions.isQuote()) {
                        sb.append("\"");
                        if (outputOptions.isEscape()) {
                            sb.append(StringEscapeUtils.escapeCsv(valueString));
                        } else {
                            sb.append(valueString);
                        }
                        sb.append("\"");
                        rowValues.add(sb.toString());
                    } else {
                        if (outputOptions.isEscape()) {
                            rowValues.add(StringEscapeUtils.escapeCsv(valueString));
                        } else {
                            rowValues.add(valueString);
                        }
                    }
                } else {
                    rowValues.add("");
                }
                break;
            case ARRAY:
            case STRUCT:
            case JAVA_OBJECT:
                String complexValueString = rs.getString(i);
                if (complexValueString != null) {
                    rowValues.add(StringEscapeUtils.escapeCsv(complexValueString));
                } else {
                    rowValues.add("");
                }
                break;
            default:
                if (value != null) {
                    rowValues.add(value.toString());
                } else {
                    rowValues.add("");
                }
            }
        }
        // Write row values
        outStream.write(
                StringUtils.join(rowValues, outputOptions.getDelimiter()).getBytes(StandardCharsets.UTF_8));
        outStream.write("\n".getBytes(StandardCharsets.UTF_8));
        nrOfRows++;
    }
    return nrOfRows;
}

From source file:org.plasma.sdo.jdbc.service.JDBCSupport.java

protected Map<String, PropertyPair> fetchRowMap(PlasmaType type, StringBuilder sql, Connection con) {
    Map<String, PropertyPair> result = new HashMap<String, PropertyPair>();
    PreparedStatement statement = null;
    ResultSet rs = null;/*from   w ww . j  a  va 2  s. c  o  m*/
    try {
        statement = con.prepareStatement(sql.toString(),
                ResultSet.TYPE_FORWARD_ONLY, /*ResultSet.TYPE_SCROLL_INSENSITIVE,*/
                ResultSet.CONCUR_READ_ONLY);

        if (log.isDebugEnabled()) {
            log.debug("fetch: " + sql.toString());
        }

        statement.execute();
        rs = statement.getResultSet();
        ResultSetMetaData rsMeta = rs.getMetaData();
        int numcols = rsMeta.getColumnCount();
        while (rs.next())
            for (int i = 1; i <= numcols; i++) {
                String columnName = rsMeta.getColumnName(i);
                int columnType = rsMeta.getColumnType(i);
                PlasmaProperty prop = (PlasmaProperty) type.getProperty(columnName);
                Object value = converter.fromJDBCDataType(rs, i, columnType, prop);
                if (value != null) {
                    PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value);
                    result.put(prop.getName(), pair);
                }
            }
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
    return result;
}

From source file:org.plasma.sdo.jdbc.service.JDBCSupport.java

protected List<PropertyPair> fetchRow(PlasmaType type, StringBuilder sql, Connection con) {
    List<PropertyPair> result = new ArrayList<PropertyPair>();
    PreparedStatement statement = null;
    ResultSet rs = null;/*w ww  .  j  a  v a2s. com*/
    try {
        statement = con.prepareStatement(sql.toString(),
                ResultSet.TYPE_FORWARD_ONLY, /*ResultSet.TYPE_SCROLL_INSENSITIVE,*/
                ResultSet.CONCUR_READ_ONLY);

        if (log.isDebugEnabled()) {
            log.debug("fetch: " + sql.toString());
        }

        statement.execute();
        rs = statement.getResultSet();
        ResultSetMetaData rsMeta = rs.getMetaData();
        int numcols = rsMeta.getColumnCount();
        while (rs.next())
            for (int i = 1; i <= numcols; i++) {
                String columnName = rsMeta.getColumnName(i);
                int columnType = rsMeta.getColumnType(i);
                PlasmaProperty prop = (PlasmaProperty) type.getProperty(columnName);
                Object value = converter.fromJDBCDataType(rs, i, columnType, prop);
                if (value != null) {
                    PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value);
                    result.add(pair);
                }
            }
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
    return result;
}

From source file:com.yahoo.dba.perf.myperf.springmvc.UdmController.java

/**
 * //from  ww w.  jav a 2  s .  c  o  m
 * Test UDM, use exception to send out message
 * @param req
 * @param udm
 * @param db
 * @throws SQLException
 */
private void testUDM(HttpServletRequest req, UserDefinedMetrics udm, String db) throws Exception {
    if (db == null || db.isEmpty())
        throw new Exception("please provide valid database for test");

    String[] dbs = db.split("\\|");
    if (dbs == null || dbs.length < 2)
        throw new Exception("please provide valid database for test");
    DBInstanceInfo dbinfo = this.frameworkContext.getDbInfoManager().findDB(dbs[0], dbs[1]);
    if (dbinfo == null)
        throw new Exception("please provide valid database for test");

    HashSet<String> metricsNameSet = new HashSet<String>();
    for (Metric m : udm.getMetrics()) {
        metricsNameSet.add(m.getSourceName());
    }
    DBConnectionWrapper connWrapper = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        String sql = udm.getSql();
        MetricsGroup mg = udm.getMetricsGroup();
        String udmType = udm.getUdmType();
        String nameCol = udm.getNameCol();
        String valCol = udm.getValueCol();
        String keyCol = udm.getKeyCol();
        boolean isBuiltin = false;
        if (!"SQL".equals(udm.getSource())) {
            sql = this.frameworkContext.getSqlTextForMetricsGroup(udm.getSource());
            mg = this.frameworkContext.getMetricsDef().getGroupByName(udm.getSource());
            if (mg != null) {
                if (mg.getKeyColumn() != null)
                    udmType = "key";
                else if (mg.isMultipleMetricsPerRow())
                    udmType = "column";
                else
                    udmType = "row";
                nameCol = mg.getMetricNameColumn();
                valCol = mg.getMetricValueColumn();
                keyCol = mg.getKeyColumn();
            }
            isBuiltin = true;
        }
        if (sql == null || sql.isEmpty()) {
            throw new Exception("please provide valid SQL");
        }
        connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo);
        if (connWrapper == null) {
            throw new Exception("failed to connect to target db (" + dbinfo + ")");
        }
        stmt = connWrapper.getConnection().createStatement();
        rs = stmt.executeQuery(sql);
        if (rs != null) {
            ResultSetMetaData meta = rs.getMetaData();
            //verify columns
            int cols = meta.getColumnCount();
            Map<String, Integer> colMap = new HashMap<String, Integer>(cols);
            for (int i = 1; i <= cols; i++)
                colMap.put(meta.getColumnName(i).toUpperCase(), meta.getColumnType(i));
            if ("row".equals(udmType)) {
                if (!colMap.containsKey(udm.getNameCol().toUpperCase()))
                    throw new Exception("Failed to find name column from SQL result: " + udm.getNameCol()
                            + ", returned: " + colMap);
                if (!colMap.containsKey(udm.getValueCol().toUpperCase()))
                    throw new Exception("Failed to find value column from SQL result: " + udm.getValueCol()
                            + ", returned: " + colMap);
            } else //check metrics column 
            {
                if ("key".equals(udmType)) {
                    if (!colMap.containsKey(keyCol.toUpperCase()))
                        throw new Exception("Failed to find key column from SQL result: " + udm.getKeyCol());
                }
                for (Metric m : udm.getMetrics()) {
                    if (!colMap.containsKey(m.getSourceName().toUpperCase()))
                        throw new Exception(
                                "Failed to find metric column from SQL result: " + m.getSourceName());
                }
            }
        } else {
            throw new Exception("Failed to test SQL.");
        }
        while (rs != null && rs.next()) {
            if ("row".equals(udmType)) {
                String name = rs.getString(nameCol);
                if (!metricsNameSet.contains(name))
                    continue;
                String val = rs.getString(valCol);
                try {
                    BigDecimal d = new BigDecimal(val == null ? "0" : val);
                } catch (Exception ex) {
                    throw new Exception("Expect numeric value for metric from SQL result, got " + val);
                }
            } else {
                for (Metric m : udm.getMetrics()) {
                    String val = rs.getString(m.getSourceName());
                    try {
                        BigDecimal d = new BigDecimal(val == null ? "0" : val);
                    } catch (Exception ex) {
                        throw new Exception("Expect numeric value metric value from SQL result for column "
                                + m.getShortName() + ", got " + val);
                    }
                }
            }

        }
    } finally {
        DBUtils.close(rs);
        DBUtils.close(stmt);
        WebAppUtil.closeDBConnection(req, connWrapper, true);//close it anyway
    }
}

From source file:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQLNew.java

public void convert(final String tableName, final String fileName) {
    String str = "";
    int fldLen = 0;
    int inx = 0;//from   w  ww.  ja v  a 2 s . c  om

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/mex?characterEncoding=UTF-8&autoReconnect=true", "root", "root");
        stmt = conn.createStatement();

        int[] fieldLengths = null;

        BasicSQLUtils.deleteAllRecordsFromTable(conn, tableName, SERVERTYPE.MySQL);
        Vector<Integer> types = new Vector<Integer>();
        Vector<String> names = new Vector<String>();

        String selectStr = null;
        String prepareStr = null;
        try {
            prepareStr = FileUtils.readFileToString(new File("prepare_stmt.txt"));
            selectStr = FileUtils.readFileToString(new File("select.txt"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        int idInx = selectStr.indexOf("ID,");
        if (idInx == 0) {
            selectStr = selectStr.substring(3);
        }

        File file = new File("/Users/rods/Documents/" + fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        //SimpleDateFormat stf = new SimpleDateFormat("k:mm:ss");

        int rowCnt = 0;
        try {
            System.out.println(prepareStr);

            PreparedStatement pStmt = conn.prepareStatement(prepareStr);
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
            str = in.readLine();

            String[] fieldNames = StringUtils.split(str, ",");
            //String[] fieldNamesDB = StringUtils.split(selectStr, ",");

            String sql = "SELECT " + selectStr + " FROM " + tableName;
            System.out.println(sql);

            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();

            fieldLengths = new int[rsmd.getColumnCount()];
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                fieldLengths[i - 1] = rsmd.getPrecision(i);
                types.add(rsmd.getColumnType(i));
                names.add(rsmd.getColumnName(i));
                System.out.println((i > 1 ? fieldNames[i - 2] : "ID") + " / " + rsmd.getColumnName(i) + " - "
                        + rsmd.getPrecision(i));
            }

            int numCols = rsmd.getColumnCount();
            rs.close();

            System.out.println("Number of Fields: " + numCols);

            str = in.readLine();
            while (str != null) {
                //System.err.println(str);

                str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", "|");

                Vector<String> fields = split(str);
                if (fields.size() != numCols) {
                    System.out.println("numCols: " + numCols + " != " + fields.size() + "fields.size()");
                    continue;
                }

                int col = 1;
                inx = 0;
                for (String fld : fields) {
                    String field = fld.trim();
                    //if (field.length() > 1)
                    //{
                    //    field = field.substring(1, field.length()-1);
                    //}
                    //if (inx > 204) break;

                    fldLen = field.length();

                    pStmt.setObject(col, null);

                    switch (types.get(inx)) {
                    case java.sql.Types.LONGVARCHAR:
                    case java.sql.Types.VARCHAR:
                    case java.sql.Types.LONGNVARCHAR: {
                        if (field.length() > 0) {
                            if (field.length() <= fieldLengths[inx]) {
                                pStmt.setString(col, field);
                            } else {
                                System.err.println(String.format("The data for `%s` (%d) is too big %d f[%s]",
                                        names.get(inx), fieldLengths[inx], field.length(), field));
                                pStmt.setString(col, null);
                            }
                        } else {
                            pStmt.setString(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.DOUBLE:
                    case java.sql.Types.FLOAT: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setDouble(col, field.length() > 0 ? Double.parseDouble(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.INTEGER: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setInt(col, field.length() > 0 ? Integer.parseInt(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.TIME: {
                        Time time = null;
                        try {
                            time = Time.valueOf(field);
                        } catch (Exception ex) {
                        }
                        pStmt.setTime(col, time);
                    }
                        break;

                    case java.sql.Types.DATE: {
                        try {
                            if (StringUtils.isNotEmpty(field)) {
                                if (StringUtils.contains(field, "/")) {
                                    field = StringUtils.replace(field, "/", "-");
                                } else if (StringUtils.contains(field, " ")) {
                                    field = StringUtils.replace(field, " ", "-");
                                }
                                pStmt.setDate(col,
                                        field.length() > 0 ? new java.sql.Date(sdf.parse(field).getTime())
                                                : null);
                            } else {
                                pStmt.setDate(col, null);
                            }
                        } catch (Exception ex) {
                            System.err.println(col + " Bad Date[" + field + "]\n" + str);
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    default: {
                        System.err.println("Error - " + types.get(inx));
                    }
                    }
                    inx++;
                    col++;
                }
                pStmt.execute();
                str = in.readLine();
                rowCnt++;
            }
            in.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (Exception e) {
            System.err.println("Row: " + rowCnt);
            System.err.println(str);
            System.err.println(inx + "  " + fieldLengths[inx] + " - Field Len: " + fldLen);
            e.printStackTrace();
        }

        /*BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        while (bis.available() > 0)
        {
        int bytesRead = bis.read(bytes);
        if (bytesRead > 0)
        {
            System.arraycopy(bytes, bytesRead, buffer, bufEndInx, bytesRead);
            bufEndInx += bytesRead;
            int inx = 0;
            while (inx < bufEndInx)
            {
                if (buffer[inx] != '\n')
                {
                    String line = 
                }
                inx++;
            }
        }
        }*/

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            stmt.close();
            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}