Example usage for java.sql PreparedStatement setCharacterStream

List of usage examples for java.sql PreparedStatement setCharacterStream

Introduction

In this page you can find the example usage for java.sql PreparedStatement setCharacterStream.

Prototype

void setCharacterStream(int parameterIndex, java.io.Reader reader, long length) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Reader object, which is the given number of characters long.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(url, username, password);
    conn.setAutoCommit(false);//from w w  w. j  ava2s. com

    String sql = "INSERT INTO documents (name, description, data) VALUES (?, ?, ?)";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setString(1, "a.txt");
    stmt.setString(2, "b");

    File data = new File("C:\\a.txt");
    FileReader reader = new FileReader(data);
    stmt.setCharacterStream(3, reader, (int) data.length());
    stmt.execute();

    conn.commit();
    reader.close();
    conn.close();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement stmt = conn.createStatement();

    stmt.executeUpdate("create table survey (id int, name BINARY);");

    String sql = "INSERT INTO survey (name) VALUES(?)";
    PreparedStatement pstmt = conn.prepareStatement(sql);

    File file = new File("yourFileName.txt");
    long fileLength = file.length();
    Reader fileReader = (Reader) new BufferedReader(new FileReader(file));

    pstmt.setCharacterStream(1, fileReader, (int) fileLength);

    int rowCount = pstmt.executeUpdate();

    ResultSet rs = stmt.executeQuery("SELECT * FROM survey");
    while (rs.next()) {
        System.out.println(rs.getBytes(2));
    }/*from  w w w . j a va 2  s  .  c  om*/

    rs.close();
    stmt.close();
    conn.close();
}

From source file:DemoPreparedStatementSetCharacterStream.java

public static void main(String[] args) throws Exception {
    String fileName = "charDataFile.txt";
    Reader fileReader = null;/*from  w w  w  .  ja v a 2s .  c om*/
    long fileLength = 0;
    Connection conn = null;
    PreparedStatement pstmt = null;

    try {
        File file = new File(fileName);
        fileLength = file.length();
        fileReader = (Reader) new BufferedReader(new FileReader(file));
        System.out.println("fileName=" + fileName);
        System.out.println("fileLength=" + fileLength);

        conn = getConnection();
        // begin transaction
        conn.setAutoCommit(false);
        // prepare SQL query for inserting a new row using SetCharacterStream()
        String query = "insert into char_stream_table (id, char_stream_column) values(?, ?)";
        // create PrepareStatement object
        pstmt = conn.prepareStatement(query);
        pstmt.setString(1, fileName);
        pstmt.setCharacterStream(2, fileReader, (int) fileLength);
        // execute query, and return number of rows created
        int rowCount = pstmt.executeUpdate();
        System.out.println("rowCount=" + rowCount);
        // end transaction
        conn.commit();
    } finally {
        pstmt.close();
        conn.close();
    }
}

From source file:jeeves.resources.dbms.Dbms.java

private void setObject(PreparedStatement stmt, int i, Object obj) throws SQLException {
    if (obj instanceof String) {
        String s = (String) obj;

        if (s.length() < 4000)
            stmt.setString(i + 1, s);//from w  w  w  .j  a v a 2 s  . c om
        else
            stmt.setCharacterStream(i + 1, new StringReader(s), s.length());
    } else
        stmt.setObject(i + 1, obj);
}

From source file:com.wabacus.config.database.type.Oracle.java

public void setClobValue(int iindex, String value, PreparedStatement pstmt) throws SQLException {
    if (value == null)
        value = "";
    BufferedReader reader = new BufferedReader(new StringReader(value));
    pstmt.setCharacterStream(iindex, reader, value.length());
}

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

public void testLobTempFiles() throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, DATA CLOB)");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
    for (int i = 0; i < 5; i++) {
        prep.setInt(1, i);/* w w w.  j  av a2  s. co m*/
        if (i % 2 == 0) {
            prep.setCharacterStream(2, new StringReader(getString(i)), -1);
        }
        prep.execute();
    }
    ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
    int check = 0;
    for (int i = 0; i < 5; i++) {
        assertTrue(rs.next());
        if (i % 2 == 0) {
            check = i;
        }
        assertEquals(getString(check), rs.getString(2));
    }
    assertFalse(rs.next());
    stat.execute("DELETE FROM TEST");
    for (int i = 0; i < 3; i++) {
        prep.setInt(1, i);
        prep.setCharacterStream(2, new StringReader(getString(i)), -1);
        prep.addBatch();
    }
    prep.executeBatch();
    rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
    for (int i = 0; i < 3; i++) {
        assertTrue(rs.next());
        assertEquals(getString(i), rs.getString(2));
    }
    assertFalse(rs.next());
    stat.execute("DROP TABLE TEST");
}

From source file:dk.netarkivet.common.utils.DBUtils.java

/**
 * Set the CLOB maxlength./* w  ww  .  j  a  v  a  2  s  .com*/
 * If contents.length() > maxSize, contents is truncated to contain
 * the first maxSize characters of the contents, and a warning is logged.
 * @param s a prepared statement
 * @param fieldNum the field-index, where the contents are inserted
 * @param contents the contents
 * @param maxSize the maxsize for this contents
 * @param o the Object, which is assumed to have a field named fieldName
 * @param fieldName a given field (Assumed to present in Object o)
 * @throws SQLException If fieldNum does not correspond to a
 * parameter marker in the PreparedStatement, or a database access error
 * occurs or this method is called on a closed PreparedStatement
 */
public static void setClobMaxLength(PreparedStatement s, int fieldNum, String contents, long maxSize, Object o,
        String fieldName) throws SQLException {
    ArgumentNotValid.checkNotNull(s, "PreparedStatement s");
    if (contents != null) {
        if (contents.length() > maxSize) {
            log.warn("The field '" + fieldName + "' is " + contents.length() + " characters long, which is "
                    + (contents.length() - maxSize) + " longer than the allowed " + maxSize
                    + " characters. The contents is now truncated to " + "length " + maxSize);
            // This caused OOM if both the 'contents' and o.toString() was large
            // (See NAS-2015).
            // It is therefore omitted from this log-entry.

            // truncate to length maxSize (if maxSize <= Integer.MAX_VALUE)
            // else truncate to length Integer.MAX_VALUE
            if (maxSize > Integer.MAX_VALUE) {
                log.warn("The maxSize is larger than maxint (" + Integer.MAX_VALUE
                        + "), which is not allowed. MaxSize changed to maxint");
                maxSize = Integer.MAX_VALUE;
            }
            contents = contents.substring(0, (int) maxSize);
        }
        s.setCharacterStream(fieldNum, new StringReader(contents), contents.length());
        s.setString(fieldNum, contents);
    } else {
        s.setNull(fieldNum, Types.CLOB);
    }
}

From source file:com.amazon.carbonado.repo.jdbc.OracleSupportStrategy.java

/**
 * @return original clob if too large and post-insert update is required, null otherwise
 *//*  w  ww.j  a  v a  2  s  .c o  m*/
@Override
com.amazon.carbonado.lob.Clob setClobValue(PreparedStatement ps, int column, com.amazon.carbonado.lob.Clob clob)
        throws PersistException {
    try {
        long length = clob.getLength();
        if (length > CLOB_CHUNK_LIMIT || ((long) ((int) length)) != length) {
            if (mCLOB_empty_lob == null) {
                return super.setClobValue(ps, column, clob);
            }

            try {
                ps.setClob(column, (java.sql.Clob) mCLOB_empty_lob.invoke(null));
                return clob;
            } catch (InvocationTargetException e) {
                throw mRepo.toPersistException(e.getCause());
            } catch (Exception e) {
                throw mRepo.toPersistException(e);
            }
        }

        if (clob instanceof OracleClob) {
            ps.setClob(column, ((OracleClob) clob).getInternalClobForPersist());
            return null;
        }

        ps.setCharacterStream(column, clob.openReader(), (int) length);
        return null;
    } catch (SQLException e) {
        throw mRepo.toPersistException(e);
    } catch (FetchException e) {
        throw e.toPersistException();
    }
}

From source file:com.jaspersoft.jasperserver.util.JasperJdbcContainer.java

/**
 * Given a array of jdbc parameters and a PreparedStatment loops through the parameter array
 * and populates the PreparedStatement/*from  w ww.  j av  a 2 s. c om*/
 * @param params jdbc parameters extracted from a CachedRowSet 
 * @param pstmt  the PreparedStatment to populate
 * @throws SQLException
 */
private void insertParameters(Object[] params, PreparedStatement pstmt) throws SQLException {

    Object[] param = null;

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

        if (params[i] instanceof Object[]) {
            param = (Object[]) params[i];
            if (param.length == 2) {
                if (param[0] == null) {
                    pstmt.setNull(i + 1, ((Integer) param[1]).intValue());
                    continue;
                }

                if (param[0] instanceof java.sql.Date || param[0] instanceof java.sql.Time
                        || param[0] instanceof java.sql.Timestamp) {
                    if (param[1] instanceof java.util.Calendar) {
                        pstmt.setDate(i + 1, (java.sql.Date) param[0], (java.util.Calendar) param[1]);
                        continue;
                    } else {
                        throw new SQLException("Unknown Parameter, expected java.util.Calendar");
                    }
                }

                if (param[0] instanceof Reader) {
                    pstmt.setCharacterStream(i + 1, (Reader) param[0], ((Integer) param[1]).intValue());
                    continue;
                }

                /*
                 * What's left should be setObject(int, Object, scale)
                 */
                if (param[1] instanceof Integer) {
                    pstmt.setObject(i + 1, param[0], ((Integer) param[1]).intValue());
                    continue;
                }

            } else if (param.length == 3) {

                if (param[0] == null) {
                    pstmt.setNull(i + 1, ((Integer) param[1]).intValue(), (String) param[2]);
                    continue;
                }

                // need to find and fix inputstreams
                if (param[0] instanceof java.io.InputStream) {
                    //logger.fine("Found parameter of type input stream");
                } //inputstream if

                /*
                 * no point at looking at the first element now; what's left
                 * must be the setObject() cases.
                 */
                if (param[1] instanceof Integer && param[2] instanceof Integer) {
                    pstmt.setObject(i + 1, param[0], ((Integer) param[1]).intValue(),
                            ((Integer) param[2]).intValue());
                    continue;
                }
                throw new SQLException("Unexpected Parameter");

            } else {
                // common case - this catches all SQL92 types
                pstmt.setObject(i + 1, params[i]);
                continue;
            }
        } else {
            // Try to get all the params to be set here
            pstmt.setObject(i + 1, params[i]);
            //logger.finest("Param" + i+ ": " + params[i]);
        }
    } //for
      //logger.exiting(getClass().getName(), "insertParameters");
}

From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java

public void updatePageTemplParam(Document ptpDoc) throws VerticalUpdateException {

    Element root = ptpDoc.getDocumentElement();
    String tmp;/* w  w  w  .  j ava  2  s .  co  m*/

    // check: does root element exist?
    if (root == null) {
        String message = "Root element does not exist";
        VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
    }

    // check: if root element is not contentrating, throw create exception
    if (!"pagetemplateparameter".equals(root.getTagName())
            && !"pagetemplateparameters".equals(root.getTagName())) {
        String message = "Root element is not the \"pagetemplateparameter\" or \"pagetemplateparameters\" element: %0";
        VerticalEngineLogger.errorUpdate(this.getClass(), 1, message, root.getTagName(), null);
    }

    Node[] node;
    if ("pagetemplateparameters".equals(root.getTagName())) {
        node = XMLTool.filterNodes(root.getChildNodes(), Node.ELEMENT_NODE);
        if (node == null || node.length == 0) {
            return;
            //String message = "No page template parameters to create.";
            //VerticalEngineLogger.warn(2, message, null);
        }
    } else {
        node = new Node[] { root };
    }

    // connection variables
    Connection con = null;
    PreparedStatement preparedStmt = null;
    //int result = -1;

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(PTP_UPDATE);

        for (Node aNode : node) {

            Element elem = (Element) aNode;
            Map<String, Element> subelems = XMLTool.filterElements(elem.getChildNodes());

            // attribute: key
            tmp = elem.getAttribute("key");
            int pageTemplParamKey = Integer.parseInt(tmp);
            preparedStmt.setInt(6, pageTemplParamKey);

            tmp = elem.getAttribute("pagetemplatekey");
            preparedStmt.setInt(1, Integer.parseInt(tmp));

            tmp = elem.getAttribute("multiple");
            preparedStmt.setInt(3, Integer.parseInt(tmp));

            tmp = elem.getAttribute("override");
            preparedStmt.setInt(5, Integer.parseInt(tmp));

            // element: name
            Element subelem = subelems.get("name");
            String name = XMLTool.getElementText(subelem);
            preparedStmt.setCharacterStream(2, new StringReader(name), name.length());

            subelem = subelems.get("separator");
            String separator = XMLTool.getElementText(subelem);
            if (separator == null || separator.length() == 0) {
                separator = "";
            }
            preparedStmt.setCharacterStream(4, new StringReader(separator), separator.length());

            int result = preparedStmt.executeUpdate();
            if (result <= 0) {
                String message = "Failed to update page template parameters. None updated.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 3, message, null);
            }
        }
    } catch (SQLException sqle) {
        String message = "Failed to update page template parameters because of database error: %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 4, message, sqle);
    } catch (NumberFormatException nfe) {
        String message = "Failed to parse a key field: %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 5, message, nfe);
    } finally {
        close(preparedStmt);
        close(con);
    }

}