Example usage for java.sql PreparedStatement setNString

List of usage examples for java.sql PreparedStatement setNString

Introduction

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

Prototype

void setNString(int parameterIndex, String value) throws SQLException;

Source Link

Document

Sets the designated parameter to the given String object.

Usage

From source file:org.athenasource.framework.unidbi.Datatypes.java

/**
 * Setting the parameter for the given prepared statement. This method will
 * cast the value to the object expected type (execept BOOLEAN) as
 * {@linkplain #getClass(int)}./*from   www  .  jav  a 2s  .c om*/
 * <p>INSERT, UPDATE should always call this method to set parameters before 'WHERE' keyword.</p>
 * <p><b>Warining</b>: For parameters after 'WHERE' keyword, always remember 'IS NULL' is not equal to '= NULL'.</p>
 *
 * @param index
 *            the parameter index
 * @param value
 *            the value for the parameter, can be <code>null</code>.
 * @param unidbType
 *            the datatype of the parameter
 * @throws SQLException
 *             in case of SQL problems or type conversion fails.
 */
public static void setParameter(PreparedStatement stmt, int index, Object value, int unidbType)
        throws SQLException {
    // Derby needs special handling.
    boolean isDerby = (stmt instanceof DelegatingPreparedStatement)
            ? ((DelegatingPreparedStatement) stmt).getDelegate().getClass().getName().contains("derby")
            : stmt.getClass().getName().contains("derby");
    if (value == null) {
        if (isDerby) {
            if (unidbType == NCHAR) {
                stmt.setNull(index, Datatypes.getSQLType(CHAR));
            } else if (unidbType == NVARCHAR) {
                stmt.setNull(index, Datatypes.getSQLType(VARCHAR));
            } else {
                stmt.setNull(index, Datatypes.getSQLType(unidbType));
            }
        } else {
            stmt.setNull(index, Datatypes.getSQLType(unidbType));
        }
    } else {
        try {
            switch (unidbType) {
            case BOOLEAN:
                stmt.setByte(index, (byte) (((Number) value).intValue() == 1 ? 1 : 0));
                break;
            case TINYINT:
                stmt.setByte(index, ((Number) value).byteValue());
                break;
            case SMALLINT:
                stmt.setShort(index, ((Number) value).shortValue());
                break;
            case INTEGER:
                stmt.setInt(index, ((Number) value).intValue());
                break;
            case BIGINT:
                stmt.setLong(index, ((Number) value).longValue());
                break;
            case DECIMAL:
                stmt.setBigDecimal(index, ((BigDecimal) value));
                break;
            case REAL:
                stmt.setFloat(index, ((Float) value).floatValue());
                break;
            case DOUBLE:
                stmt.setDouble(index, ((Double) value).doubleValue());
                break;
            case CHAR:
                stmt.setString(index, (String) value);
                break;
            case NCHAR:
                if (isDerby) {
                    stmt.setString(index, (String) value);
                } else {
                    stmt.setNString(index, (String) value);
                }
                break;
            case VARCHAR:
                stmt.setString(index, (String) value);
                break;
            case NVARCHAR:
                if (isDerby) {
                    stmt.setString(index, (String) value);
                } else {
                    stmt.setNString(index, (String) value);
                }
                break;
            case CLOB: // Clob/NClob can be represented as String without any problem. - Oct 16, 2008.
                stmt.setString(index, (String) value); // stmt.setClob(index, ((Clob) value));
                break;
            case NCLOB:
                if (isDerby) {
                    stmt.setString(index, (String) value);
                } else {
                    stmt.setNString(index, (String) value); // stmt.setNClob(index, ((NClob) value));
                }
                break;
            case BLOB:
                stmt.setBlob(index, ((Blob) value));
                break;
            case TIMESTAMP:
                stmt.setTimestamp(index, ((Timestamp) value));
                break;
            default:
                throw new IllegalArgumentException("[!NO SUCH UNIDB DATA TYPE: " + unidbType + "]");
            }
        } catch (ClassCastException cce) {
            throw new SQLException(
                    "Failed to convert " + value + " (" + value.getClass() + ") to " + getName(unidbType));
        }
    }
}

From source file:org.nuxeo.App.java

public static void main(String[] args) throws SQLException, IOException {

    Properties prop = readProperties();
    String user = prop.getProperty("user");
    String password = prop.getProperty("password");
    String connectionURL = prop.getProperty("url");
    String driver = prop.getProperty("driver");
    String query = prop.getProperty("query");

    log.info("Connect to:" + connectionURL + " from " + getHostName());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(baos);
    final ConsoleReporter reporter = new ConsoleReporter(printStream);

    Connection conn = null;/*ww w . ja v  a  2s . com*/
    PreparedStatement ps = null;
    ResultSet rs = null;
    TimerContext tc = null;
    int repeat = Integer.valueOf(System.getProperty(REPEAT_KEY, DEFAULT_REPEAT)).intValue();

    log.info("Submiting " + repeat + " queries: " + query);
    try {
        Class.forName(driver);
        tc = connTimer.time();
        conn = DriverManager.getConnection(connectionURL, user, password);
        tc.stop();
        ps = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        int paramCount = countOccurrences(query, '?');
        for (int i = 1; i <= paramCount; i++) {
            String key = "p" + i;
            String param = prop.getProperty(key);
            if (param == null) {
                break;
            }
            log.info(key + " = " + param);
            String type = "object";
            if (param.contains(":")) {
                type = param.split(":", 2)[0];
                param = param.split(":", 2)[1];
            }
            if (type.equalsIgnoreCase("object")) {
                ps.setObject(i, (Object) param);
            } else if (type.equalsIgnoreCase("string")) {
                ps.setString(i, param);
            } else if (type.equalsIgnoreCase("nstring")) {
                ps.setNString(i, param);
            } else {
                log.warn("Unknown type " + type + " use setObject");
                ps.setObject(i, (Object) param);
            }
        }

        int rows = 0;
        int bytes = 0;

        for (int i = 0; i < repeat; i++) {
            tc = execTimer.time();
            rs = ps.executeQuery();
            tc.stop();
            tc = fetchingTimer.time();
            ResultSetMetaData rsmd = rs.getMetaData();
            int cols = rsmd.getColumnCount();
            while (rs.next()) {
                rows++;
                for (int c = 1; c <= cols; c++) {
                    bytes += rs.getBytes(1).length;
                }
            }
            rs.close();
            tc.stop();
            // don't stress too much
            Thread.sleep((int) (Math.random() * 100));
        }
        log.info("Fetched rows: " + rows + ", total bytes: " + bytes + ", bytes/rows: "
                + ((float) bytes) / rows);

    } catch (SQLException e) {
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (ps != null) {
            ps.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
    reporter.run();
    try {
        String content = baos.toString("ISO-8859-1");
        log.info(content);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    }

}

From source file:org.springframework.jdbc.core.StatementCreatorUtils.java

private static void setValue(PreparedStatement ps, int paramIndex, int sqlType, @Nullable String typeName,
        @Nullable Integer scale, Object inValue) throws SQLException {

    if (inValue instanceof SqlTypeValue) {
        ((SqlTypeValue) inValue).setTypeValue(ps, paramIndex, sqlType, typeName);
    } else if (inValue instanceof SqlValue) {
        ((SqlValue) inValue).setValue(ps, paramIndex);
    } else if (sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR) {
        ps.setString(paramIndex, inValue.toString());
    } else if (sqlType == Types.NVARCHAR || sqlType == Types.LONGNVARCHAR) {
        ps.setNString(paramIndex, inValue.toString());
    } else if ((sqlType == Types.CLOB || sqlType == Types.NCLOB) && isStringValue(inValue.getClass())) {
        String strVal = inValue.toString();
        if (strVal.length() > 4000) {
            // Necessary for older Oracle drivers, in particular when running against an Oracle 10 database.
            // Should also work fine against other drivers/databases since it uses standard JDBC 4.0 API.
            if (sqlType == Types.NCLOB) {
                ps.setNClob(paramIndex, new StringReader(strVal), strVal.length());
            } else {
                ps.setClob(paramIndex, new StringReader(strVal), strVal.length());
            }//w w w  . j a va 2  s  . com
            return;
        } else {
            // Fallback: setString or setNString binding
            if (sqlType == Types.NCLOB) {
                ps.setNString(paramIndex, strVal);
            } else {
                ps.setString(paramIndex, strVal);
            }
        }
    } else if (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC) {
        if (inValue instanceof BigDecimal) {
            ps.setBigDecimal(paramIndex, (BigDecimal) inValue);
        } else if (scale != null) {
            ps.setObject(paramIndex, inValue, sqlType, scale);
        } else {
            ps.setObject(paramIndex, inValue, sqlType);
        }
    } else if (sqlType == Types.BOOLEAN) {
        if (inValue instanceof Boolean) {
            ps.setBoolean(paramIndex, (Boolean) inValue);
        } else {
            ps.setObject(paramIndex, inValue, Types.BOOLEAN);
        }
    } else if (sqlType == Types.DATE) {
        if (inValue instanceof java.util.Date) {
            if (inValue instanceof java.sql.Date) {
                ps.setDate(paramIndex, (java.sql.Date) inValue);
            } else {
                ps.setDate(paramIndex, new java.sql.Date(((java.util.Date) inValue).getTime()));
            }
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setDate(paramIndex, new java.sql.Date(cal.getTime().getTime()), cal);
        } else {
            ps.setObject(paramIndex, inValue, Types.DATE);
        }
    } else if (sqlType == Types.TIME) {
        if (inValue instanceof java.util.Date) {
            if (inValue instanceof java.sql.Time) {
                ps.setTime(paramIndex, (java.sql.Time) inValue);
            } else {
                ps.setTime(paramIndex, new java.sql.Time(((java.util.Date) inValue).getTime()));
            }
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setTime(paramIndex, new java.sql.Time(cal.getTime().getTime()), cal);
        } else {
            ps.setObject(paramIndex, inValue, Types.TIME);
        }
    } else if (sqlType == Types.TIMESTAMP) {
        if (inValue instanceof java.util.Date) {
            if (inValue instanceof java.sql.Timestamp) {
                ps.setTimestamp(paramIndex, (java.sql.Timestamp) inValue);
            } else {
                ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
            }
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal);
        } else {
            ps.setObject(paramIndex, inValue, Types.TIMESTAMP);
        }
    } else if (sqlType == SqlTypeValue.TYPE_UNKNOWN || (sqlType == Types.OTHER
            && "Oracle".equals(ps.getConnection().getMetaData().getDatabaseProductName()))) {
        if (isStringValue(inValue.getClass())) {
            ps.setString(paramIndex, inValue.toString());
        } else if (isDateValue(inValue.getClass())) {
            ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal);
        } else {
            // Fall back to generic setObject call without SQL type specified.
            ps.setObject(paramIndex, inValue);
        }
    } else {
        // Fall back to generic setObject call with SQL type specified.
        ps.setObject(paramIndex, inValue, sqlType);
    }
}

From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java

/**
 * This method bind values to prepared statement.
 *
 * @param type            data Type/*from   w ww  .j a v a2s .  co  m*/
 * @param value           String value
 * @param ordinalPosition Ordinal Position
 * @param sqlStatement    Statement
 * @throws SQLException
 * @throws ParseException
 * @throws ODataServiceFault
 */
private void bindValuesToPreparedStatement(int type, String value, int ordinalPosition,
        PreparedStatement sqlStatement) throws SQLException, ParseException, ODataServiceFault {
    byte[] data;
    try {
        switch (type) {
        case Types.INTEGER:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setInt(ordinalPosition, ConverterUtil.convertToInt(value));
            }
            break;
        case Types.TINYINT:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setByte(ordinalPosition, ConverterUtil.convertToByte(value));
            }
            break;
        case Types.SMALLINT:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setShort(ordinalPosition, ConverterUtil.convertToShort(value));
            }
            break;
        case Types.DOUBLE:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setDouble(ordinalPosition, ConverterUtil.convertToDouble(value));
            }
            break;
        case Types.VARCHAR:
            /* fall through */
        case Types.CHAR:
            /* fall through */
        case Types.LONGVARCHAR:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setString(ordinalPosition, value);
            }
            break;
        case Types.CLOB:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setClob(ordinalPosition, new BufferedReader(new StringReader(value)),
                        value.length());
            }
            break;
        case Types.BOOLEAN:
            /* fall through */
        case Types.BIT:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setBoolean(ordinalPosition, ConverterUtil.convertToBoolean(value));
            }
            break;
        case Types.BLOB:
            /* fall through */
        case Types.LONGVARBINARY:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                data = this.getBytesFromBase64String(value);
                sqlStatement.setBlob(ordinalPosition, new ByteArrayInputStream(data), data.length);
            }
            break;
        case Types.BINARY:
            /* fall through */
        case Types.VARBINARY:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                data = this.getBytesFromBase64String(value);
                sqlStatement.setBinaryStream(ordinalPosition, new ByteArrayInputStream(data), data.length);
            }
            break;
        case Types.DATE:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setDate(ordinalPosition, DBUtils.getDate(value));
            }
            break;
        case Types.DECIMAL:
            /* fall through */
        case Types.NUMERIC:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setBigDecimal(ordinalPosition, ConverterUtil.convertToBigDecimal(value));
            }
            break;
        case Types.FLOAT:
            /* fall through */
        case Types.REAL:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setFloat(ordinalPosition, ConverterUtil.convertToFloat(value));
            }
            break;
        case Types.TIME:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setTime(ordinalPosition, DBUtils.getTime(value));
            }
            break;
        case Types.LONGNVARCHAR:
            /* fall through */
        case Types.NCHAR:
            /* fall through */
        case Types.NVARCHAR:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setNString(ordinalPosition, value);
            }
            break;
        case Types.NCLOB:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setNClob(ordinalPosition, new BufferedReader(new StringReader(value)),
                        value.length());
            }
            break;
        case Types.BIGINT:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setLong(ordinalPosition, ConverterUtil.convertToLong(value));
            }
            break;
        case Types.TIMESTAMP:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setTimestamp(ordinalPosition, DBUtils.getTimestamp(value));
            }
            break;
        default:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setString(ordinalPosition, value);
            }
            break;
        }
    } catch (DataServiceFault e) {
        throw new ODataServiceFault(e, "Error occurred while binding values. :" + e.getMessage());
    }
}