List of usage examples for java.sql PreparedStatement getParameterMetaData
ParameterMetaData getParameterMetaData() throws SQLException;
PreparedStatement
object's parameters. From source file:io.kamax.mxisd.backend.wordpress.WordpressDirectoryProvider.java
protected void setParameters(PreparedStatement stmt, String searchTerm) throws SQLException { for (int i = 1; i <= stmt.getParameterMetaData().getParameterCount(); i++) { stmt.setString(i, "%" + searchTerm + "%"); }/*from ww w . j a va 2s .co m*/ }
From source file:org.apache.eagle.metadata.store.jdbc.service.orm.SiteEntityToRelation.java
@Override public void accept(PreparedStatement statement, SiteEntity entity) throws SQLException { int parameterIndex = 1; boolean addNullValue = (statement.getParameterMetaData().getParameterCount() > 5); if (addNullValue || StringUtils.isNotBlank(entity.getSiteId())) { statement.setString(parameterIndex, entity.getSiteId()); parameterIndex++;//from w w w.j a v a 2 s . co m } if (addNullValue || StringUtils.isNotBlank(entity.getSiteName())) { statement.setString(parameterIndex, entity.getSiteName()); parameterIndex++; } if (addNullValue || StringUtils.isNotBlank(entity.getDescription())) { statement.setString(parameterIndex, entity.getDescription()); parameterIndex++; } if (entity.getCreatedTime() > 0) { statement.setLong(parameterIndex, entity.getCreatedTime()); parameterIndex++; } if (entity.getModifiedTime() > 0) { statement.setLong(parameterIndex, entity.getModifiedTime()); parameterIndex++; } if (StringUtils.isNotBlank(entity.getUuid())) { statement.setString(parameterIndex, entity.getUuid()); parameterIndex++; } }
From source file:com.espertech.esper.epl.db.DatabasePollingViewableFactory.java
private static QueryMetaData getPreparedStmtMetadata(Connection connection, String[] parameters, String preparedStatementText, ColumnSettings metadataSetting) throws ExprValidationException { PreparedStatement prepared; try {// w ww.j a va 2 s. c o m if (log.isInfoEnabled()) { log.info(".getPreparedStmtMetadata Preparing statement '" + preparedStatementText + "'"); } prepared = connection.prepareStatement(preparedStatementText); } catch (SQLException ex) { String text = "Error preparing statement '" + preparedStatementText + '\''; log.error(text, ex); throw new ExprValidationException(text + ", reason: " + ex.getMessage()); } // Interrogate prepared statement - parameters and result List<String> inputParameters = new LinkedList<String>(); try { ParameterMetaData parameterMetaData = prepared.getParameterMetaData(); inputParameters.addAll(Arrays.asList(parameters).subList(0, parameterMetaData.getParameterCount())); } catch (Exception ex) { try { prepared.close(); } catch (SQLException e) { // don't handle } String text = "Error obtaining parameter metadata from prepared statement, consider turning off metadata interrogation via configuration, for statement '" + preparedStatementText + '\''; log.error(text, ex); throw new ExprValidationException(text + ", please check the statement, reason: " + ex.getMessage()); } Map<String, DBOutputTypeDesc> outputProperties; try { outputProperties = compileResultMetaData(prepared.getMetaData(), metadataSetting); } catch (SQLException ex) { try { prepared.close(); } catch (SQLException e) { // don't handle } String text = "Error in statement '" + preparedStatementText + "', failed to obtain result metadata, consider turning off metadata interrogation via configuration"; log.error(text, ex); throw new ExprValidationException(text + ", please check the statement, reason: " + ex.getMessage()); } if (log.isDebugEnabled()) { log.debug(".createDBEventStream in=" + inputParameters.toString() + " out=" + outputProperties.toString()); } // Close statement try { prepared.close(); } catch (SQLException e) { String text = "Error closing prepared statement"; log.error(text, e); throw new ExprValidationException(text + ", reason: " + e.getMessage()); } return new QueryMetaData(inputParameters, outputProperties); }
From source file:net.big_oh.common.jdbc.JdbcObserverProxyStatementInvocationHandler.java
private String populatePreparedStatementSQLString(PreparedStatement preparedStmnt, String preparedSQL) { String result = preparedSQL;//from w w w. ja va 2 s . c o m try { for (int i = 1; i <= preparedStmnt.getParameterMetaData().getParameterCount(); i++) { // lookup the parameter value String preparedStatementParameter = preparedStatementParameters.get(i); // handle missing parameter if (StringUtils.isBlank(preparedStatementParameter)) { preparedStatementParameter = "UNKNOWN_PARAMETER_VALUE"; } // formatting for some parameter types try { if (Arrays.asList(SQL_CHARACTER_TYPES) .contains(preparedStmnt.getParameterMetaData().getParameterType(i))) { preparedStatementParameter = "'" + preparedStatementParameter + "'"; } } catch (SQLException sqle) { // Just don't worry about formatting if proxied driver // throws SQLException logger.debug(sqle); } result = RegExpHelper.replaceFirst(result, "\\?", preparedStatementParameter); } } catch (SQLException e) { logger.error("Failed while populating prepared statement:", e); } return result; }
From source file:org.hxzon.util.db.springjdbc.StatementCreatorUtils.java
/** * Set the specified PreparedStatement parameter to null, * respecting database-specific peculiarities. *//*from www . j a v a 2 s .c om*/ private static void setNull(PreparedStatement ps, int paramIndex, int sqlType, String typeName) throws SQLException { if (sqlType == SqlTypeValue.TYPE_UNKNOWN) { boolean useSetObject = false; Integer sqlTypeToUse = null; DatabaseMetaData dbmd = null; String jdbcDriverName = null; boolean checkGetParameterType = !shouldIgnoreGetParameterType; if (checkGetParameterType && !driversWithNoSupportForGetParameterType.isEmpty()) { try { dbmd = ps.getConnection().getMetaData(); jdbcDriverName = dbmd.getDriverName(); checkGetParameterType = !driversWithNoSupportForGetParameterType.contains(jdbcDriverName); } catch (Throwable ex) { logger.debug("Could not check connection metadata", ex); } } if (checkGetParameterType) { try { sqlTypeToUse = ps.getParameterMetaData().getParameterType(paramIndex); } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug( "JDBC 3.0 getParameterType call not supported - using fallback method instead: " + ex); } } } if (sqlTypeToUse == null) { // JDBC driver not compliant with JDBC 3.0 -> proceed with database-specific checks sqlTypeToUse = Types.NULL; try { if (dbmd == null) { dbmd = ps.getConnection().getMetaData(); } if (jdbcDriverName == null) { jdbcDriverName = dbmd.getDriverName(); } if (checkGetParameterType) { driversWithNoSupportForGetParameterType.add(jdbcDriverName); } String databaseProductName = dbmd.getDatabaseProductName(); if (databaseProductName.startsWith("Informix") || jdbcDriverName.startsWith("Microsoft SQL Server")) { useSetObject = true; } else if (databaseProductName.startsWith("DB2") || jdbcDriverName.startsWith("jConnect") || jdbcDriverName.startsWith("SQLServer") || jdbcDriverName.startsWith("Apache Derby")) { sqlTypeToUse = Types.VARCHAR; } } catch (Throwable ex) { logger.debug("Could not check connection metadata", ex); } } if (useSetObject) { ps.setObject(paramIndex, null); } else { ps.setNull(paramIndex, sqlTypeToUse); } } else if (typeName != null) { ps.setNull(paramIndex, sqlType, typeName); } else { ps.setNull(paramIndex, sqlType); } }
From source file:org.batoo.jpa.core.impl.jdbc.dbutils.AbstractQueryRunner.java
/** * Fill the <code>PreparedStatement</code> replacement parameters with the given objects. * //from w ww . j ava2 s . c o m * @param stmt * PreparedStatement to fill * @param params * Query replacement parameters; <code>null</code> is a valid value to pass in. * @throws SQLException * if a database access error occurs */ public void fillStatement(PreparedStatement stmt, Object... params) throws SQLException { // check the parameter count, if we can ParameterMetaData pmd = null; if (!this.pmdKnownBroken) { pmd = stmt.getParameterMetaData(); final int stmtCount = pmd.getParameterCount(); final int paramsCount = params == null ? 0 : params.length; if (stmtCount != paramsCount) { throw new SQLException( "Wrong number of parameters: expected " + stmtCount + ", was given " + paramsCount); } } // nothing to do here if (params == null) { return; } for (int i = 0; i < params.length; i++) { if (params[i] != null) { stmt.setObject(i + 1, params[i]); } else { // VARCHAR works with many drivers regardless // of the actual column type. Oddly, NULL and // OTHER don't work with Oracle's drivers. int sqlType = Types.VARCHAR; if (!this.pmdKnownBroken) { try { sqlType = pmd.getParameterType(i + 1); } catch (final SQLException e) { this.pmdKnownBroken = true; } } stmt.setNull(i + 1, sqlType); } } }
From source file:org.tradex.jdbc.JDBCHelper.java
/** * Generates a SqlParameterSource for the passed SQL text and supplied binds * @param sql The SQL to bind to/* w w w . j a va 2 s .c o m*/ * @param binds The supplied variables to bind * @return a SqlParameterSource */ public SqlParameterSource getBinds(String sql, final Object... binds) { final MapSqlParameterSource sqlParamSource = new MapSqlParameterSource(); int[] parameterTypes = TYPE_CACHE.get(sql); if (parameterTypes == null) { synchronized (TYPE_CACHE) { parameterTypes = TYPE_CACHE.get(sql); if (parameterTypes == null) { Connection conn = null; PreparedStatement ps = null; try { conn = ds.getConnection(); ps = conn.prepareStatement(NamedParameterUtils.parseSqlStatementIntoString(sql).toString()); ParameterMetaData pmd = ps.getParameterMetaData(); int paramCount = pmd.getParameterCount(); if (paramCount > 0 && (binds == null || binds.length != paramCount)) { throw new RuntimeException("Bind Count [" + (binds == null ? 0 : binds.length) + "] was not equal to parameter count [" + paramCount + "]"); } parameterTypes = new int[paramCount]; for (int i = 0; i < paramCount; i++) { parameterTypes[i] = pmd.getParameterType(i + 1); } } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new RuntimeException("Failed to get binds for [" + sql + "]", e); } finally { try { ps.close(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } } TYPE_CACHE.put(sql, parameterTypes); } } for (int i = 0; i < parameterTypes.length; i++) { sqlParamSource.addValue("" + i, binds[i], parameterTypes[i]); } return sqlParamSource; }
From source file:org.springframework.security.provisioning.JdbcUserDetailsManager.java
public void updateUser(final UserDetails user) { validateUserDetails(user);// w w w .j a v a 2s . co m getJdbcTemplate().update(updateUserSql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, user.getPassword()); ps.setBoolean(2, user.isEnabled()); int paramCount = ps.getParameterMetaData().getParameterCount(); if (paramCount == 3) { ps.setString(3, user.getUsername()); } else { //NOTE: acc_locked, acc_expired and creds_expired are also updated ps.setBoolean(3, !user.isAccountNonLocked()); ps.setBoolean(4, !user.isAccountNonExpired()); ps.setBoolean(5, !user.isCredentialsNonExpired()); ps.setString(6, user.getUsername()); } } }); if (getEnableAuthorities()) { deleteUserAuthorities(user.getUsername()); insertUserAuthorities(user); } userCache.removeUserFromCache(user.getUsername()); }
From source file:org.zaproxy.zap.extension.sse.db.TableEventStream.java
public synchronized int getIndexOf(ServerSentEvent criteria, List<Integer> inScopeStreamIds) throws DatabaseException { try {//from w w w .jav a 2 s . c o m String query = "SELECT COUNT(e.event_id) " + "FROM event_stream_event AS e " + "<where> AND e.event_id < ?"; PreparedStatement stmt = buildEventCriteriaStatement(query, criteria, inScopeStreamIds); int paramsCount = stmt.getParameterMetaData().getParameterCount(); stmt.setInt(paramsCount, criteria.getId()); try { return executeAndGetSingleIntValue(stmt); } finally { stmt.close(); } } catch (SQLException e) { throw new DatabaseException(e); } }
From source file:org.springframework.security.provisioning.JdbcUserDetailsManager.java
public void createUser(final UserDetails user) { validateUserDetails(user);/*w w w.ja v a2s.c o m*/ getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); ps.setBoolean(3, user.isEnabled()); int paramCount = ps.getParameterMetaData().getParameterCount(); if (paramCount > 3) { //NOTE: acc_locked, acc_expired and creds_expired are also to be inserted ps.setBoolean(4, !user.isAccountNonLocked()); ps.setBoolean(5, !user.isAccountNonExpired()); ps.setBoolean(6, !user.isCredentialsNonExpired()); } } }); if (getEnableAuthorities()) { insertUserAuthorities(user); } }