Example usage for java.sql Clob getSubString

List of usage examples for java.sql Clob getSubString

Introduction

In this page you can find the example usage for java.sql Clob getSubString.

Prototype

String getSubString(long pos, int length) throws SQLException;

Source Link

Document

Retrieves a copy of the specified substring in the CLOB value designated by this Clob object.

Usage

From source file:Main.java

public static String getCLOB(int id) throws Exception {
    Connection conn = null;//  w  w w .j  a  v a  2s . c  om
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    String query = "SELECT clobData FROM tableName WHERE id = ?";

    try {
        conn = getConnection();
        pstmt = conn.prepareStatement(query);
        pstmt.setInt(1, id);
        rs = pstmt.executeQuery();
        rs.next();
        Clob clob = rs.getClob(1);
        // materialize CLOB onto client
        String wholeClob = clob.getSubString(1, (int) clob.length());
        return wholeClob;
    } finally {
        rs.close();
        pstmt.close();
        conn.close();
    }
}

From source file:com.afforess.nsdump.Test.java

public static void testNationDump() throws IOException, SQLException {
    NationsDump dump = new NationsDump();
    dump.parse();//from  w  ww  .ja v  a2 s . c o m

    Connection conn = dump.getDatabaseConnection();
    PreparedStatement statement = conn.prepareStatement("SELECT (name) FROM nations");
    ResultSet result = statement.executeQuery();
    int total = 0;
    while (result.next()) {
        total++;
    }
    result.close();

    System.out.println("Total nations: " + total);

    statement = conn.prepareStatement("SELECT * FROM nations WHERE name = 'sakhovelo'");
    result = statement.executeQuery();
    result.next();
    for (int i = 1; i <= 10; i++) {
        if (i == 4) {
            Clob clob = result.getClob(i);
            String motto = clob.getSubString(1, (int) clob.length());
            String mottoEscaped = StringEscapeUtils.unescapeHtml(motto);
            System.out.println("Raw: " + motto + " Escaped: " + mottoEscaped);
        } else {
            System.out.println(result.getString(i));
        }
    }

    File db = new File("./ns-db.h2.db");
    db.delete();
}

From source file:cognition.pipeline.data.helper.ClobHelper.java

private String getString(Object expectedClob) {
    SerializableClobProxy clobProxy = (SerializableClobProxy) Proxy.getInvocationHandler(expectedClob);
    Clob wrappedClob = clobProxy.getWrappedClob();
    try {/*from  w w w . ja va2 s.  co  m*/
        return wrappedClob.getSubString(1, (int) wrappedClob.length());
    } catch (SQLException e) {
        e.printStackTrace();
        return "error: could not retrieve text";
    }
}

From source file:com.ccoe.build.dal.SessionMapper.java

public Session mapRow(ResultSet rs, int arg1) throws SQLException {
    Session session = new Session();
    session.setDuration(rs.getLong("duration"));
    session.setEnvironment(rs.getString("environment"));
    session.setJavaVersion(rs.getString("java_version"));
    session.setMavenVersion(rs.getString("maven_version"));
    session.setStartTime(rs.getDate("start_time"));
    session.setUserName(rs.getString("user_name"));
    session.setStatus(rs.getString("status"));
    session.setGoals(rs.getString("goals"));
    session.setAppName(rs.getString("pool_name"));
    session.setMachineName(rs.getString("machine_name"));

    Clob stacktrace = rs.getClob("full_stacktrace");
    if (stacktrace != null) {
        session.setFullStackTrace(stacktrace.getSubString(1, (int) stacktrace.length()));
    }//from  ww  w  . j a  v a2 s  .c  o  m

    session.setExceptionMessage(rs.getString("cause"));
    session.setCategory(rs.getString("category"));

    session.setId(rs.getInt("id"));

    session.setFilter(rs.getString("filter"));

    return session;
}

From source file:com.quinsoft.zeidon.dbhandler.StandardJdbcTranslator.java

/**
 * Takes a value loaded from the DB and potentially converts it.
 *///  w ww. ja  v  a  2  s.  co  m
@Override
public Object convertDbValue(Domain domain, Object dbValue) throws SQLException {
    if (dbValue instanceof Clob) {
        Clob clob = (Clob) dbValue;
        return clob.getSubString(1L, (int) clob.length());
    }

    if (domain instanceof DateDomain) {
        if (dbValue instanceof CharSequence) {
            String date = dbValue.toString();
            try {
                return this.dateFormatter.parseDateTime(date);
            } catch (IllegalArgumentException e) {
                throw ZeidonException.prependMessage(e,
                        "Invalid date format.  Got '%s' but expected format '%s'", date, dateFormatter);
            }
        } else if (dbValue instanceof Date) {
            return new DateTime(dbValue);
        }
    }

    if (domain instanceof DateTimeDomain) {
        if (dbValue instanceof CharSequence) {
            String date = dbValue.toString();
            try {
                return dateTimeFormatter.parseDateTime(date);
            } catch (IllegalArgumentException e) {
                throw ZeidonException.prependMessage(e,
                        "Invalid datetime format.  Got '%s' but expected format '%s'", date, dateTimeFormatter);
            }
        }
    }

    return dbValue;
}

From source file:ca.hec.cdm.jobs.ImportZC1CatalogDescriptionJob.java

public void execute(JobExecutionContext arg0) throws JobExecutionException {

    Connection connex = getZC1Connection();
    PreparedStatement ps = null;//from   ww w .  java 2s.c  o  m

    try {
        ps = connex.prepareStatement(ZC1_REQUEST);

        ResultSet rs = ps.executeQuery();

        while (rs.next()) {

            String koid = rs.getString(1);
            Clob htmlClob = rs.getClob(2);

            // ajouter pour la table plancours
            if (koid.substring(0, 2).equalsIgnoreCase("a-")) {
                koid = koid.substring(2);
            }

            String courseId = FormatUtils.formatCourseId(koid);

            String html = htmlClob.getSubString((long) 1, (int) htmlClob.length());
            String desc = formatHtml(html);

            if (desc != null) {
                saveInZC2(courseId, desc);
            } else {
                log.error("No description found in ZC1 for: " + courseId);
                noDesc++;
            }

        } // end while

        log.error("----------------------------------------------------------------------------------");
        log.error("FIN DE LA JOB");
        log.error("saved desc:" + savedDesc);
        log.error("unknow desc:" + unknownDesc);
        log.error("no desc found:" + noDesc);
        log.error("Description is not null:" + notNullDesc);
    } catch (SQLException sqex) {
        log.error("Error database: " + sqex.toString());
    } finally {
        try {
            ps.close();
        } catch (Exception ex) {
        }
        try {
            connex.close();
        } catch (Exception ex) {
        }
    }

}

From source file:com.oracle.tutorial.jdbc.ClobSample.java

public String retrieveExcerpt(String coffeeName, int numChar) throws SQLException {

    String description = null;/*from   w ww .  j  a v  a  2s  .  c om*/
    Clob myClob = null;
    PreparedStatement pstmt = null;

    try {
        String sql = "select COF_DESC from COFFEE_DESCRIPTIONS " + "where COF_NAME = ?";
        pstmt = this.con.prepareStatement(sql);
        pstmt.setString(1, coffeeName);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            myClob = rs.getClob(1);
            System.out.println("Length of retrieved Clob: " + myClob.length());
        }
        description = myClob.getSubString(1, numChar);
    } catch (SQLException sqlex) {
        JDBCTutorialUtilities.printSQLException(sqlex);
    } catch (Exception ex) {
        System.out.println("Unexpected exception: " + ex.toString());
    } finally {
        if (pstmt != null)
            pstmt.close();
    }
    return description;
}

From source file:com.netspective.axiom.sql.StoredProcedureParameter.java

/**
 * Extract the OUT parameter values from the callable statment and
 * assign them to the value of the parameter.
 *//*from w w  w  .jav  a2 s .c o  m*/
public void extract(ConnectionContext cc, CallableStatement stmt) throws SQLException {
    if (getType().getValueIndex() == StoredProcedureParameter.Type.IN)
        return;

    int index = this.getIndex();
    QueryParameterType paramType = getSqlType();
    int jdbcType = paramType.getJdbcType();
    String identifier = paramType.getIdentifier();

    // result sets are special
    if (identifier.equals(QueryParameterType.RESULTSET_IDENTIFIER)) {
        ResultSet rs = (ResultSet) stmt.getObject(index);
        QueryResultSet qrs = new QueryResultSet(getParent().getProcedure(), cc, rs);
        value.getValue(cc).setValue(qrs);
        return;
    }

    switch (jdbcType) {
    case Types.VARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case Types.INTEGER:
        value.getValue(cc).setValue(new Integer(stmt.getInt(index)));
        break;
    case Types.DOUBLE:
        value.getValue(cc).setValue(new Double(stmt.getDouble(index)));
        break;
    case Types.CLOB:
        Clob clob = stmt.getClob(index);
        value.getValue(cc).setTextValue(clob.getSubString(1, (int) clob.length()));
        break;
    case java.sql.Types.ARRAY:
        Array array = stmt.getArray(index);
        value.getValue(cc).setValue(array);
        break;
    case java.sql.Types.BIGINT:
        long bigint = stmt.getLong(index);
        value.getValue(cc).setValue(new Long(bigint));
        break;
    case java.sql.Types.BINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.BIT:
        boolean bit = stmt.getBoolean(index);
        value.getValue(cc).setValue(new Boolean(bit));
    case java.sql.Types.BLOB:
        value.getValue(cc).setValue(stmt.getBlob(index));
        break;
    case java.sql.Types.CHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case java.sql.Types.DATE:
        value.getValue(cc).setValue(stmt.getDate(index));
        break;
    case java.sql.Types.DECIMAL:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.DISTINCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.FLOAT:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    case java.sql.Types.JAVA_OBJECT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.LONGVARBINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.LONGVARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    //case java.sql.Types.NULL:
    //    value.getValue(cc).setValue(null);
    //    break;
    case java.sql.Types.NUMERIC:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.OTHER:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.REAL:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    //case java.sql.Types.REF:
    //    Ref ref = stmt.getRef(index);
    //    break;
    case java.sql.Types.SMALLINT:
        short sh = stmt.getShort(index);
        value.getValue(cc).setValue(new Short(sh));
        break;
    case java.sql.Types.STRUCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.TIME:
        value.getValue(cc).setValue(stmt.getTime(index));
        break;
    case java.sql.Types.TIMESTAMP:
        value.getValue(cc).setValue(stmt.getTimestamp(index));
        break;
    case java.sql.Types.TINYINT:
        byte b = stmt.getByte(index);
        value.getValue(cc).setValue(new Byte(b));
        break;
    case java.sql.Types.VARBINARY:
        value.getValue(cc).setValue(stmt.getBytes(index));
        break;
    default:
        throw new RuntimeException(
                "Unknown JDBC Type set for stored procedure parameter '" + this.getName() + "'.");
    }
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * @return an appropriate CharSequence representation of the given object.
 * @usage _advanced_method_//from ww  w.ja v a  2  s.  c o  m
 */
public static CharSequence toCharSequence(Object value) throws IOException {
    if (value == null) {
        return null;
    } else if (value instanceof CharSequence) {
        return (CharSequence) value;
    } else if (value instanceof Clob) {
        try {
            Clob c = (Clob) value;
            // note, start pos is 1-based
            return c.getSubString(1L, (int) c.length());
        } catch (SQLException e) {
            throw (IOException) (new IOException(e.getMessage())).initCause(e);
        }
    } else if (value instanceof Reader) {
        char[] buf = new char[8 * 1024];
        StringBuilder sout = new StringBuilder();
        Reader in = (Reader) value;
        int read = 0;
        while ((read = in.read(buf)) != -1) {
            sout.append(buf, 0, read);
        }
        return sout;
    }

    return value.toString();
}

From source file:dk.netarkivet.harvester.datamodel.JobDBDAO.java

/** Try to extract an orderxmldoc from a given Clob.
 * This method is used by the read() method, which catches the
 * thrown DocumentException.//from  w w  w .ja  v  a  2  s.c om
 * @param clob a given Clob returned from the database
 * @return a Document object based on the data in the Clob
 * @throws SQLException If data from the clob cannot be fetched.
 * @throws DocumentException If unable to create a Document object based on
 * the data in the Clob
 */
private Document getOrderXMLdocFromClob(Clob clob) throws SQLException, DocumentException {
    Document doc;
    try {
        SAXReader reader = new SAXReader();
        doc = reader.read(clob.getCharacterStream());
    } catch (DocumentException e) {
        log.warn("Failed to read the contents of the clob as XML:" + clob.getSubString(1, (int) clob.length()));
        throw e;
    }
    return doc;
}