Example usage for org.springframework.jdbc.core.namedparam MapSqlParameterSource addValue

List of usage examples for org.springframework.jdbc.core.namedparam MapSqlParameterSource addValue

Introduction

In this page you can find the example usage for org.springframework.jdbc.core.namedparam MapSqlParameterSource addValue.

Prototype

public MapSqlParameterSource addValue(String paramName, @Nullable Object value, int sqlType) 

Source Link

Document

Add a parameter to this parameter source.

Usage

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//from w ww.ja v  a  2  s  . co 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;
}