Search in sources :

Example 41 with ResultSetMetaData

use of java.sql.ResultSetMetaData in project MSEC by Tencent.

the class DBUtil method findSimpleRefResult.

//查询数据库,只返回一条记录, 使用java反射机制,将记录映射到java类T
public <T> T findSimpleRefResult(String sql, List<Object> params, Class<T> cls) throws Exception {
    T resultObject = null;
    int index = 1;
    pstmt = connection.prepareStatement(sql);
    if (params != null && !params.isEmpty()) {
        for (int i = 0; i < params.size(); i++) {
            pstmt.setObject(index++, params.get(i));
        }
    }
    resultSet = pstmt.executeQuery();
    ResultSetMetaData metaData = resultSet.getMetaData();
    int cols_len = metaData.getColumnCount();
    while (resultSet.next()) {
        resultObject = cls.newInstance();
        for (int i = 0; i < cols_len; i++) {
            String cols_name = metaData.getColumnName(i + 1);
            Object cols_value = resultSet.getObject(cols_name);
            if (cols_value == null) {
                cols_value = "";
            }
            Field field = cls.getDeclaredField(cols_name);
            field.setAccessible(true);
            field.set(resultObject, cols_value);
        }
    }
    resultSet.close();
    pstmt.close();
    return resultObject;
}
Also used : ResultSetMetaData(java.sql.ResultSetMetaData) Field(java.lang.reflect.Field)

Example 42 with ResultSetMetaData

use of java.sql.ResultSetMetaData in project MSEC by Tencent.

the class DBUtil method findMoreRefResult.

//查询数据库,返回所有满足条件的记录, 使用java反射机制,将记录映射到java类T
public <T> ArrayList<T> findMoreRefResult(String sql, List<Object> params, Class<T> cls) throws Exception {
    ArrayList<T> list = new ArrayList<T>();
    int index = 1;
    pstmt = connection.prepareStatement(sql);
    if (params != null && !params.isEmpty()) {
        for (int i = 0; i < params.size(); i++) {
            pstmt.setObject(index++, params.get(i));
        }
    }
    resultSet = pstmt.executeQuery();
    ResultSetMetaData metaData = resultSet.getMetaData();
    int cols_len = metaData.getColumnCount();
    while (resultSet.next()) {
        T resultObject = cls.newInstance();
        for (int i = 0; i < cols_len; i++) {
            String cols_name = metaData.getColumnName(i + 1);
            Object cols_value = resultSet.getObject(cols_name);
            if (cols_value == null) {
                cols_value = "";
            }
            Field field = cls.getDeclaredField(cols_name);
            //��javabean�ķ���Ȩ��
            field.setAccessible(true);
            field.set(resultObject, cols_value);
        }
        list.add(resultObject);
    }
    resultSet.close();
    pstmt.close();
    return list;
}
Also used : ResultSetMetaData(java.sql.ResultSetMetaData) Field(java.lang.reflect.Field)

Example 43 with ResultSetMetaData

use of java.sql.ResultSetMetaData in project sonarqube by SonarSource.

the class AbstractDbTester method getHashMap.

private static List<Map<String, Object>> getHashMap(ResultSet resultSet) throws Exception {
    ResultSetMetaData metaData = resultSet.getMetaData();
    int colCount = metaData.getColumnCount();
    List<Map<String, Object>> rows = newArrayList();
    while (resultSet.next()) {
        Map<String, Object> columns = newHashMap();
        for (int i = 1; i <= colCount; i++) {
            Object value = resultSet.getObject(i);
            if (value instanceof Clob) {
                Clob clob = (Clob) value;
                value = IOUtils.toString((clob.getAsciiStream()));
                doClobFree(clob);
            } else if (value instanceof BigDecimal) {
                // In Oracle, INTEGER types are mapped as BigDecimal
                BigDecimal bgValue = ((BigDecimal) value);
                if (bgValue.scale() == 0) {
                    value = bgValue.longValue();
                } else {
                    value = bgValue.doubleValue();
                }
            } else if (value instanceof Integer) {
                // To be consistent, all INTEGER types are mapped as Long
                value = ((Integer) value).longValue();
            }
            columns.put(metaData.getColumnLabel(i), value);
        }
        rows.add(columns);
    }
    return rows;
}
Also used : ResultSetMetaData(java.sql.ResultSetMetaData) Clob(java.sql.Clob) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Maps.newHashMap(com.google.common.collect.Maps.newHashMap) BigDecimal(java.math.BigDecimal)

Example 44 with ResultSetMetaData

use of java.sql.ResultSetMetaData in project generator by mybatis.

the class DatabaseIntrospector method getColumns.

/**
     * This method returns a Map<ActualTableName, List<ColumnDefinitions>> of columns returned from the database
     * introspection.
     *
     * @param tc
     *            the tc
     * @return introspected columns
     * @throws SQLException
     *             the SQL exception
     */
private Map<ActualTableName, List<IntrospectedColumn>> getColumns(TableConfiguration tc) throws SQLException {
    String localCatalog;
    String localSchema;
    String localTableName;
    boolean delimitIdentifiers = tc.isDelimitIdentifiers() || stringContainsSpace(tc.getCatalog()) || stringContainsSpace(tc.getSchema()) || stringContainsSpace(tc.getTableName());
    if (delimitIdentifiers) {
        localCatalog = tc.getCatalog();
        localSchema = tc.getSchema();
        localTableName = tc.getTableName();
    } else if (databaseMetaData.storesLowerCaseIdentifiers()) {
        localCatalog = tc.getCatalog() == null ? null : tc.getCatalog().toLowerCase();
        localSchema = tc.getSchema() == null ? null : tc.getSchema().toLowerCase();
        localTableName = tc.getTableName() == null ? null : tc.getTableName().toLowerCase();
    } else if (databaseMetaData.storesUpperCaseIdentifiers()) {
        localCatalog = tc.getCatalog() == null ? null : tc.getCatalog().toUpperCase();
        localSchema = tc.getSchema() == null ? null : tc.getSchema().toUpperCase();
        localTableName = tc.getTableName() == null ? null : tc.getTableName().toUpperCase();
    } else {
        localCatalog = tc.getCatalog();
        localSchema = tc.getSchema();
        localTableName = tc.getTableName();
    }
    if (tc.isWildcardEscapingEnabled()) {
        String escapeString = databaseMetaData.getSearchStringEscape();
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;
        if (localSchema != null) {
            //$NON-NLS-1$
            st = new StringTokenizer(localSchema, "_%", true);
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                if (//$NON-NLS-1$
                token.equals("_") || token.equals("%")) {
                    //$NON-NLS-1$
                    sb.append(escapeString);
                }
                sb.append(token);
            }
            localSchema = sb.toString();
        }
        sb.setLength(0);
        //$NON-NLS-1$
        st = new StringTokenizer(localTableName, "_%", true);
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (//$NON-NLS-1$
            token.equals("_") || token.equals("%")) {
                //$NON-NLS-1$
                sb.append(escapeString);
            }
            sb.append(token);
        }
        localTableName = sb.toString();
    }
    Map<ActualTableName, List<IntrospectedColumn>> answer = new HashMap<ActualTableName, List<IntrospectedColumn>>();
    if (logger.isDebugEnabled()) {
        String fullTableName = composeFullyQualifiedTableName(localCatalog, localSchema, localTableName, '.');
        //$NON-NLS-1$
        logger.debug(getString("Tracing.1", fullTableName));
    }
    ResultSet rs = databaseMetaData.getColumns(localCatalog, localSchema, localTableName, //$NON-NLS-1$
    "%");
    boolean supportsIsAutoIncrement = false;
    boolean supportsIsGeneratedColumn = false;
    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();
    for (int i = 1; i <= colCount; i++) {
        if ("IS_AUTOINCREMENT".equals(rsmd.getColumnName(i))) {
            //$NON-NLS-1$
            supportsIsAutoIncrement = true;
        }
        if ("IS_GENERATEDCOLUMN".equals(rsmd.getColumnName(i))) {
            //$NON-NLS-1$
            supportsIsGeneratedColumn = true;
        }
    }
    while (rs.next()) {
        IntrospectedColumn introspectedColumn = ObjectFactory.createIntrospectedColumn(context);
        introspectedColumn.setTableAlias(tc.getAlias());
        //$NON-NLS-1$
        introspectedColumn.setJdbcType(rs.getInt("DATA_TYPE"));
        //$NON-NLS-1$
        introspectedColumn.setLength(rs.getInt("COLUMN_SIZE"));
        //$NON-NLS-1$
        introspectedColumn.setActualColumnName(rs.getString("COLUMN_NAME"));
        introspectedColumn.setNullable(//$NON-NLS-1$
        rs.getInt("NULLABLE") == DatabaseMetaData.columnNullable);
        //$NON-NLS-1$
        introspectedColumn.setScale(rs.getInt("DECIMAL_DIGITS"));
        //$NON-NLS-1$
        introspectedColumn.setRemarks(rs.getString("REMARKS"));
        //$NON-NLS-1$
        introspectedColumn.setDefaultValue(rs.getString("COLUMN_DEF"));
        if (supportsIsAutoIncrement) {
            //$NON-NLS-1$ //$NON-NLS-2$
            introspectedColumn.setAutoIncrement("YES".equals(rs.getString("IS_AUTOINCREMENT")));
        }
        if (supportsIsGeneratedColumn) {
            //$NON-NLS-1$ //$NON-NLS-2$
            introspectedColumn.setGeneratedColumn("YES".equals(rs.getString("IS_GENERATEDCOLUMN")));
        }
        ActualTableName atn = new ActualTableName(//$NON-NLS-1$
        rs.getString("TABLE_CAT"), //$NON-NLS-1$
        rs.getString("TABLE_SCHEM"), //$NON-NLS-1$
        rs.getString("TABLE_NAME"));
        List<IntrospectedColumn> columns = answer.get(atn);
        if (columns == null) {
            columns = new ArrayList<IntrospectedColumn>();
            answer.put(atn, columns);
        }
        columns.add(introspectedColumn);
        if (logger.isDebugEnabled()) {
            logger.debug(getString(//$NON-NLS-1$
            "Tracing.2", introspectedColumn.getActualColumnName(), Integer.toString(introspectedColumn.getJdbcType()), atn.toString()));
        }
    }
    closeResultSet(rs);
    if (answer.size() > 1 && !stringContainsSQLWildcard(localSchema) && !stringContainsSQLWildcard(localTableName)) {
        // issue a warning if there is more than one table and
        // no wildcards were used
        ActualTableName inputAtn = new ActualTableName(tc.getCatalog(), tc.getSchema(), tc.getTableName());
        StringBuilder sb = new StringBuilder();
        boolean comma = false;
        for (ActualTableName atn : answer.keySet()) {
            if (comma) {
                sb.append(',');
            } else {
                comma = true;
            }
            sb.append(atn.toString());
        }
        warnings.add(getString(//$NON-NLS-1$
        "Warning.25", inputAtn.toString(), sb.toString()));
    }
    return answer;
}
Also used : HashMap(java.util.HashMap) Messages.getString(org.mybatis.generator.internal.util.messages.Messages.getString) JavaBeansUtil.getCamelCaseString(org.mybatis.generator.internal.util.JavaBeansUtil.getCamelCaseString) ResultSetMetaData(java.sql.ResultSetMetaData) StringTokenizer(java.util.StringTokenizer) IntrospectedColumn(org.mybatis.generator.api.IntrospectedColumn) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List)

Example 45 with ResultSetMetaData

use of java.sql.ResultSetMetaData in project mybatis-3 by mybatis.

the class Jdbc3KeyGenerator method processBatch.

public void processBatch(MappedStatement ms, Statement stmt, Collection<Object> parameters) {
    ResultSet rs = null;
    try {
        rs = stmt.getGeneratedKeys();
        final Configuration configuration = ms.getConfiguration();
        final TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        final String[] keyProperties = ms.getKeyProperties();
        final ResultSetMetaData rsmd = rs.getMetaData();
        TypeHandler<?>[] typeHandlers = null;
        if (keyProperties != null && rsmd.getColumnCount() >= keyProperties.length) {
            for (Object parameter : parameters) {
                // there should be one row for each statement (also one for each parameter)
                if (!rs.next()) {
                    break;
                }
                final MetaObject metaParam = configuration.newMetaObject(parameter);
                if (typeHandlers == null) {
                    typeHandlers = getTypeHandlers(typeHandlerRegistry, metaParam, keyProperties, rsmd);
                }
                populateKeys(rs, metaParam, keyProperties, typeHandlers);
            }
        }
    } catch (Exception e) {
        throw new ExecutorException("Error getting generated key or setting result to parameter object. Cause: " + e, e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            // ignore
            }
        }
    }
}
Also used : ResultSetMetaData(java.sql.ResultSetMetaData) TypeHandlerRegistry(org.apache.ibatis.type.TypeHandlerRegistry) ExecutorException(org.apache.ibatis.executor.ExecutorException) Configuration(org.apache.ibatis.session.Configuration) MetaObject(org.apache.ibatis.reflection.MetaObject) ResultSet(java.sql.ResultSet) MetaObject(org.apache.ibatis.reflection.MetaObject) TypeHandler(org.apache.ibatis.type.TypeHandler) ExecutorException(org.apache.ibatis.executor.ExecutorException) SQLException(java.sql.SQLException)

Aggregations

ResultSetMetaData (java.sql.ResultSetMetaData)449 ResultSet (java.sql.ResultSet)279 SQLException (java.sql.SQLException)125 Statement (java.sql.Statement)123 Test (org.junit.Test)109 PreparedStatement (java.sql.PreparedStatement)107 ArrayList (java.util.ArrayList)78 Connection (java.sql.Connection)68 HashMap (java.util.HashMap)44 DatabaseMetaData (java.sql.DatabaseMetaData)41 Map (java.util.Map)31 LinkedHashMap (java.util.LinkedHashMap)22 List (java.util.List)18 IOException (java.io.IOException)15 BigDecimal (java.math.BigDecimal)12 HashSet (java.util.HashSet)12 ParameterMetaData (java.sql.ParameterMetaData)10 Properties (java.util.Properties)10 KnownFailure (dalvik.annotation.KnownFailure)9 Field (java.lang.reflect.Field)9