Example usage for java.sql ResultSetMetaData getColumnName

List of usage examples for java.sql ResultSetMetaData getColumnName

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnName.

Prototype

String getColumnName(int column) throws SQLException;

Source Link

Document

Get the designated column's name.

Usage

From source file:ips1ap101.lib.core.db.xdp.RecursoCachedRowSet.java

private String columnName(int columnIndex) {
    try {//from   w w  w.  j  a  v a2  s.c o m
        ResultSetMetaData rsmd = getMetaData();
        return rsmd.getColumnName(columnIndex);
    } catch (SQLException ex) {
        TLC.getBitacora().fatal(ex);
    }
    return null;
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

public String getRecordsAsJson(String sql, JsonKeyCase jsonKeyCase, Boolean useCamelCase, Boolean escapeHtml,
        SimpleDateFormat dateFormatter, Object... params) {
    PreparedStatement st = null;/*from   www  . ja  v  a2  s . com*/
    ResultSet rs = null;
    ResultSetMetaData rsMetaData = null;
    Gson gson = new Gson();
    try {
        StringBuilder stringBuilder = null;
        stringBuilder = new StringBuilder("[");
        st = conn.prepareStatement(sql);
        setParams(st, params);
        rs = st.executeQuery();
        rsMetaData = rs.getMetaData();
        while (rs.next()) {
            stringBuilder.append("{");
            for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {
                String attrName;
                switch (jsonKeyCase) {
                case UPPER:
                    attrName = rsMetaData.getColumnName(i).toUpperCase();
                    break;
                case LOWER:
                    attrName = rsMetaData.getColumnName(i).toLowerCase();
                    break;
                default:
                    attrName = rsMetaData.getColumnName(i);
                }
                String test = dbToFieldName(attrName);
                stringBuilder.append("\"").append((useCamelCase) ? dbToFieldName(attrName) : attrName)
                        .append("\":");
                Object val = rs.getObject(i);
                if (val == null) {
                    stringBuilder.append("null,");
                } else if (val instanceof Number) {
                    stringBuilder.append(val.toString()).append(",");
                } else if (val instanceof java.sql.Date) {
                    stringBuilder.append("\"")
                            .append(dateFormatter.format(new java.util.Date(((java.sql.Date) val).getTime())))
                            .append("\",");
                } else if (val instanceof java.sql.Timestamp) {
                    stringBuilder.append("\"")
                            .append(dateFormatter
                                    .format(new java.util.Date(((java.sql.Timestamp) val).getTime())))
                            .append("\",");
                } else {
                    if (escapeHtml)
                        stringBuilder.append(gson.toJson(rs.getObject(i).toString())).append(",");
                    else
                        stringBuilder.append("\"").append(rs.getObject(i).toString()).append("\",");
                }
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            stringBuilder.append("},");
        }
        if (stringBuilder.length() > 1)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        stringBuilder.append("]");
        return stringBuilder.toString();
    } catch (Exception ex) {
        throw new DataQueryException(sql, null, ex);
    } finally {
        closeOnFinally(rs, st);
    }

}

From source file:mil.army.usace.data.nativequery.rdbms.NativeRdbmsQuery.java

public String getRecordsAsJson(String sql, Object... params) {
    PreparedStatement st = null;/*from ww  w . ja v a2 s  .c o  m*/
    ResultSet rs = null;
    ResultSetMetaData rsMetaData = null;
    try {
        StringBuilder stringBuilder = null;
        stringBuilder = new StringBuilder("[");
        st = conn.prepareStatement(sql);
        setParams(st, params);
        rs = st.executeQuery();
        rsMetaData = rs.getMetaData();
        while (rs.next()) {
            stringBuilder.append("{");
            for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {
                String val;
                if (rs.getObject(i) == null) {
                    val = "";
                } else {
                    val = StringEscapeUtils.escapeJavaScript(rs.getObject(i).toString());
                }
                stringBuilder.append("\"").append(rsMetaData.getColumnName(i)).append("\":\"").append(val)
                        .append("\",");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            stringBuilder.append("},");
        }
        if (stringBuilder.length() > 1)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        stringBuilder.append("]");
        return stringBuilder.toString();
    } catch (Exception ex) {
        throw new NativeQueryException(sql, null, ex);
    } finally {
        closeOnFinally(rs, st);
    }

}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

/**
 * Create a column group and confirm that the {@code ResultSetMetaData} works.
 *///from   w  ww . j  a va2s  . c o  m
@Test
public void testResultSetMetaData() throws Exception {

    Statement stmt = con.createStatement();

    // Create the target Column family
    String createCF = "CREATE COLUMNFAMILY t33 (k int PRIMARY KEY," + "c text " + ") ;";

    stmt.execute(createCF);
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));

    // paraphrase of the snippet from the ISSUE #33 provided test
    PreparedStatement statement = con.prepareStatement("update t33 set c=? where k=123");
    statement.setString(1, "mark");
    statement.executeUpdate();

    ResultSet result = statement.executeQuery("SELECT k, c FROM t33;");

    ResultSetMetaData metadata = result.getMetaData();

    int colCount = metadata.getColumnCount();

    System.out.println("Test Issue #33");
    DatabaseMetaData md = con.getMetaData();
    System.out.println();
    System.out.println("--------------");
    System.out.println("Driver Version :   " + md.getDriverVersion());
    System.out.println("DB Version     :   " + md.getDatabaseProductVersion());
    System.out.println("Catalog term   :   " + md.getCatalogTerm());
    System.out.println("Catalog        :   " + con.getCatalog());
    System.out.println("Schema term    :   " + md.getSchemaTerm());

    System.out.println("--------------");
    while (result.next()) {
        metadata = result.getMetaData();
        colCount = metadata.getColumnCount();

        assertEquals("Total column count should match schema for t33", 2, metadata.getColumnCount());

        System.out.printf("(%d) ", result.getRow());
        for (int i = 1; i <= colCount; i++) {
            System.out.print(showColumn(i, result) + " ");

            switch (i) {
            case 1:
                assertEquals("First Column: k", "k", metadata.getColumnName(1));
                assertEquals("First Column Type: int", Types.INTEGER, metadata.getColumnType(1));
                break;
            case 2:
                assertEquals("Second Column: c", "c", metadata.getColumnName(2));
                assertEquals("Second Column Type: text", Types.NVARCHAR, metadata.getColumnType(2));
                break;
            }
        }
        System.out.println();
    }
}

From source file:org.ensembl.healthcheck.util.DBUtils.java

public static boolean compareResultSets(ResultSet rs1, ResultSet rs2, EnsTestCase testCase, String text,
        boolean reportErrors, boolean warnNull, String singleTableName, int[] columns,
        boolean comparingSchema) {

    // quick tests first
    // Check for object equality
    if (rs1.equals(rs2)) {
        return true;
    }//from   w  w  w . j  a  v  a2  s .c o  m

    try {

        // get some information about the ResultSets
        String name1 = getShortDatabaseName(rs1.getStatement().getConnection());
        String name2 = getShortDatabaseName(rs2.getStatement().getConnection());

        // Check for same column count, names and types
        ResultSetMetaData rsmd1 = rs1.getMetaData();
        ResultSetMetaData rsmd2 = rs2.getMetaData();
        if (rsmd1.getColumnCount() != rsmd2.getColumnCount() && columns == null) {

            if (reportErrors) {

                ReportManager.problem(testCase, name1, "Column counts differ " + singleTableName + " " + name1
                        + ": " + rsmd1.getColumnCount() + " " + name2 + ": " + rsmd2.getColumnCount());
            }

            return false; // Deliberate early return for performance
            // reasons
        }

        if (columns == null) {
            columns = new int[rsmd1.getColumnCount()];
            for (int i = 0; i < columns.length; i++) {
                columns[i] = i + 1;
            }
        }

        for (int j = 0; j < columns.length; j++) {
            int i = columns[j];

            // note columns indexed from l
            if (!((rsmd1.getColumnName(i)).equals(rsmd2.getColumnName(i)))) {

                if (reportErrors) {

                    ReportManager.problem(testCase, name1,
                            "Column names differ for " + singleTableName + " column " + i + " - " + name1 + ": "
                                    + rsmd1.getColumnName(i) + " " + name2 + ": " + rsmd2.getColumnName(i));
                }

                // Deliberate early return for performance reasons
                return false;

            }
            if (rsmd1.getColumnType(i) != rsmd2.getColumnType(i)) {

                if (reportErrors) {

                    ReportManager.problem(testCase, name1,
                            "Column types differ for " + singleTableName + " column " + i + " - " + name1 + ": "
                                    + rsmd1.getColumnType(i) + " " + name2 + ": " + rsmd2.getColumnType(i));
                }
                return false; // Deliberate early return for performance
                // reasons
            }
        } // for column

        // make sure both cursors are at the start of the ResultSet
        // (default is before the start)
        rs1.beforeFirst();
        rs2.beforeFirst();
        // if quick checks didn't cause return, try comparing row-wise

        int row = 1;
        while (rs1.next()) {

            if (rs2.next()) {
                String str = name1 + " and " + name2 + text + " " + singleTableName + " with columns ";
                for (int j = 0; j < columns.length; j++) {
                    int i = columns[j];
                    str += rsmd1.getColumnName(i) + " " + Utils.truncate(rs1.getString(i), 250, true) + ", ";
                    // note columns indexed from 1
                    if (!compareColumns(rs1, rs2, i, warnNull)) {
                        str += " differ for values " + Utils.truncate(rs1.getString(i), 250, true) + ", "
                                + Utils.truncate(rs2.getString(i), 250, true);
                        if (reportErrors) {
                            ReportManager.problem(testCase, name1, str);
                        }
                        return false;
                    }
                }
                row++;

            } else {
                // rs1 has more rows than rs2
                if (reportErrors) {
                    ReportManager.problem(testCase, name1,
                            singleTableName + " has more rows in " + name1 + " than in " + name2);
                }
                return false;
            }

        } // while rs1

        // if both ResultSets are the same, then we should be at the end of
        // both, i.e. .next() should return false
        String extra = comparingSchema ? ". This means that there are missing columns in the table, rectify!"
                : "";
        if (rs1.next()) {

            if (reportErrors) {
                ReportManager.problem(testCase, name1, name1 + " " + singleTableName
                        + " has additional rows that are not in " + name2 + extra);
            }
            return false;
        } else if (rs2.next()) {

            if (reportErrors) {
                ReportManager.problem(testCase, name1, name2 + " " + singleTableName
                        + " has additional rows that are not in " + name1 + extra);

            }
            return false;
        }

    } catch (SQLException se) {
        throw new SqlUncheckedException("Could not compare two result sets", se);
    }

    return true;

}

From source file:com.funambol.json.coredb.dao.DBManager.java

public List<Map<String, String>> executeQuery(String query, DataFilter... filters) throws Exception {
    log.info("Executing query [" + query + "].");
    if (ds == null)
        throw new Exception("Data source is null.");

    Connection connection = null;
    Statement stmt = null;/*from w  w w.  j ava  2 s  .  co m*/
    ResultSet rsltSet = null;
    ResultSetMetaData metadata = null;

    try {
        connection = ds.getConnection();
    } catch (SQLException ex) {
        release(connection, stmt, rsltSet);
        throw new Exception("An error occurred retrieving connection.", ex);
    }

    if (connection == null) {
        throw new Exception("Connection is null.");
    }

    try {
        stmt = connection.createStatement();
    } catch (SQLException ex) {
        release(connection, stmt, rsltSet);
        throw new Exception("An error occurred creating statement.", ex);
    }

    try {
        rsltSet = stmt.executeQuery(query);
        metadata = rsltSet.getMetaData();
    } catch (SQLException ex) {
        release(connection, stmt, rsltSet);
        throw new Exception("An error occurred executing query [" + query + "].", ex);
    }

    try {
        if (rsltSet != null) {

            Map<String, DataFilter> columnNamesFilters = new HashMap<String, DataFilter>();
            Map<String, DataFilter> columnClassFilters = new HashMap<String, DataFilter>();
            populateFilterMap(columnNamesFilters, columnClassFilters, filters);

            List<Map<String, String>> result = new ArrayList<Map<String, String>>();
            int numberOfColumns = metadata.getColumnCount();
            while (rsltSet.next()) {
                Map<String, String> newItem = new HashMap<String, String>();
                for (int i = 1; i <= numberOfColumns; i++) {
                    String columnName = metadata.getColumnName(i);
                    String columnValue = null;
                    String columnClass = metadata.getColumnClassName(i);
                    // Retrieving filter bound to column class or column name
                    DataFilter filter = null;
                    if (!columnNamesFilters.isEmpty() && columnNamesFilters.containsKey(columnName)) {
                        filter = columnNamesFilters.get(columnName);
                    } else if (!columnClassFilters.isEmpty() && columnClassFilters.containsKey(columnClass)) {
                        filter = columnClassFilters.get(columnClass);
                    }

                    if (filter != null) {
                        Object obj = rsltSet.getObject(i);
                        columnValue = filter.applyFilter(obj);
                    } else
                        columnValue = rsltSet.getString(i);

                    newItem.put(columnName, columnValue);
                }
                result.add(newItem);
            }
            return result;

        } else
            throw new Exception("ResultSet is null.");
    } catch (SQLException ex) {
        throw new Exception("An error occurred creating result list for query [" + query + "].", ex);
    } finally {
        release(connection, stmt, rsltSet);
    }

}

From source file:com.glaf.core.util.DBUtils.java

public static void alterTable(String systemName, String tableName, List<ColumnDefinition> columns) {
    Connection conn = null;/*  w w w.java2s  .  c  o  m*/
    PreparedStatement pstmt = null;
    ResultSetMetaData rsmd = null;
    Statement stmt = null;
    ResultSet rs = null;
    List<String> columnNames = new java.util.ArrayList<String>();
    try {
        conn = DBConnectionFactory.getConnection();
        conn.setAutoCommit(false);
        pstmt = conn.prepareStatement(" select * from " + tableName + " where 1=0 ");
        rs = pstmt.executeQuery();
        rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {
            columnNames.add(rsmd.getColumnName(i).toLowerCase());
        }

        if (columns != null && !columns.isEmpty()) {
            String dbType = DBConnectionFactory.getDatabaseType(conn);
            for (ColumnDefinition column : columns) {
                if (columnNames.contains(column.getColumnName().toLowerCase())) {
                    continue;
                }
                String javaType = column.getJavaType();
                String sql = " alter table " + tableName + " add " + column.getColumnName();
                if ("db2".equalsIgnoreCase(dbType)) {
                    if ("String".equals(javaType)) {
                        if (column.getLength() > 0) {
                            sql += " varchar(" + column.getLength() + ")";
                        } else {
                            sql += " varchar(50) ";
                        }
                    } else if ("Integer".equals(javaType)) {
                        sql += " integer ";
                    } else if ("Long".equals(javaType)) {
                        sql += " bigint ";
                    } else if ("Double".equals(javaType)) {
                        sql += " double precision ";
                    } else if ("Date".equals(javaType)) {
                        sql += " timestamp ";
                    } else if ("Clob".equals(javaType)) {
                        sql += " clob(10240000) ";
                    } else if ("Blob".equals(javaType)) {
                        sql += " blob ";
                    } else if ("Boolean".equals(javaType)) {
                        sql += " smallint ";
                    }
                } else if ("oracle".equalsIgnoreCase(dbType)) {
                    if ("String".equals(javaType)) {
                        if (column.getLength() > 0) {
                            sql += " NVARCHAR2(" + column.getLength() + ")";
                        } else {
                            sql += " NVARCHAR2(50)";
                        }
                    } else if ("Integer".equals(javaType)) {
                        sql += " INTEGER ";
                    } else if ("Long".equals(javaType)) {
                        sql += " NUMBER(19,0) ";
                    } else if ("Double".equals(javaType)) {
                        sql += " NUMBER(*,10) ";
                    } else if ("Date".equals(javaType)) {
                        sql += " TIMESTAMP(6) ";
                    } else if ("Clob".equals(javaType)) {
                        sql += " CLOB ";
                    } else if ("Blob".equals(javaType)) {
                        sql += " BLOB ";
                    } else if ("Boolean".equals(javaType)) {
                        sql += " NUMBER(1,0) ";
                    }
                } else if ("mysql".equalsIgnoreCase(dbType)) {
                    if ("String".equals(javaType)) {
                        if (column.getLength() > 0) {
                            sql += " varchar(" + column.getLength() + ")";
                        } else {
                            sql += " varchar(50)";
                        }
                    } else if ("Integer".equals(javaType)) {
                        sql += " int  ";
                    } else if ("Long".equals(javaType)) {
                        sql += " bigint ";
                    } else if ("Double".equals(javaType)) {
                        sql += " double ";
                    } else if ("Date".equals(javaType)) {
                        sql += " datetime ";
                    } else if ("Clob".equals(javaType)) {
                        sql += " longtext ";
                    } else if ("Blob".equals(javaType)) {
                        sql += " longblob ";
                    } else if ("Boolean".equals(javaType)) {
                        sql += " tinyint ";
                    }
                } else if ("postgresql".equalsIgnoreCase(dbType)) {
                    if ("String".equals(javaType)) {
                        if (column.getLength() > 0) {
                            sql += " varchar(" + column.getLength() + ")";
                        } else {
                            sql += " varchar(50)";
                        }
                    } else if ("Integer".equals(javaType)) {
                        sql += " integer ";
                    } else if ("Long".equals(javaType)) {
                        sql += " bigint ";
                    } else if ("Double".equals(javaType)) {
                        sql += " double precision ";
                    } else if ("Date".equals(javaType)) {
                        sql += " timestamp ";
                    } else if ("Clob".equals(javaType)) {
                        sql += " text ";
                    } else if ("Blob".equals(javaType)) {
                        sql += " bytea ";
                    } else if ("Boolean".equals(javaType)) {
                        sql += " boolean ";
                    }
                } else if ("sqlserver".equalsIgnoreCase(dbType)) {
                    if ("String".equals(javaType)) {
                        if (column.getLength() > 0) {
                            sql += " nvarchar(" + column.getLength() + ")";
                        } else {
                            sql += " nvarchar(50)";
                        }
                    } else if ("Integer".equals(javaType)) {
                        sql += " int ";
                    } else if ("Long".equals(javaType)) {
                        sql += " numeric(19,0) ";
                    } else if ("Double".equals(javaType)) {
                        sql += " double precision ";
                    } else if ("Date".equals(javaType)) {
                        sql += " datetime ";
                    } else if ("Clob".equals(javaType)) {
                        sql += " text ";
                    } else if ("Blob".equals(javaType)) {
                        sql += " image ";
                    } else if ("Boolean".equals(javaType)) {
                        sql += " tinyint ";
                    }
                } else if ("h2".equalsIgnoreCase(dbType)) {
                    if ("String".equals(javaType)) {
                        if (column.getLength() > 0) {
                            sql += " varchar(" + column.getLength() + ")";
                        } else {
                            sql += " varchar(50)";
                        }
                    } else if ("Integer".equals(javaType)) {
                        sql += " int  ";
                    } else if ("Long".equals(javaType)) {
                        sql += " bigint ";
                    } else if ("Double".equals(javaType)) {
                        sql += " double ";
                    } else if ("Date".equals(javaType)) {
                        sql += " timestamp ";
                    } else if ("Clob".equals(javaType)) {
                        sql += " clob ";
                    } else if ("Blob".equals(javaType)) {
                        sql += " longvarbinary ";
                    } else if ("Boolean".equals(javaType)) {
                        sql += " boolean ";
                    }
                } else if ("sqlite".equalsIgnoreCase(dbType)) {
                    if ("String".equals(javaType)) {
                        if (column.getLength() > 0) {
                            sql += " TEXT(" + column.getLength() + ")";
                        } else {
                            sql += " TEXT(50)";
                        }
                    } else if ("Integer".equals(javaType)) {
                        sql += " INTEGER  ";
                    } else if ("Long".equals(javaType)) {
                        sql += " INTEGER ";
                    } else if ("Double".equals(javaType)) {
                        sql += " REAL ";
                    } else if ("Date".equals(javaType)) {
                        sql += " TEXT ";
                    } else if ("Clob".equals(javaType)) {
                        sql += " TEXT ";
                    } else if ("Blob".equals(javaType)) {
                        sql += " BLOB ";
                    }
                } else {
                    if ("String".equals(javaType)) {
                        if (column.getLength() > 0) {
                            sql += " varchar(" + column.getLength() + ")";
                        } else {
                            sql += " varchar(50)";
                        }
                    } else if ("Integer".equals(javaType)) {
                        sql += " int ";
                    } else if ("Long".equals(javaType)) {
                        sql += " bigint ";
                    } else if ("Double".equals(javaType)) {
                        sql += " double ";
                    } else if ("Date".equals(javaType)) {
                        sql += " timestamp ";
                    } else if ("Clob".equals(javaType)) {
                        sql += " clob ";
                    } else if ("Blob".equals(javaType)) {
                        sql += " blob ";
                    } else if ("Boolean".equals(javaType)) {
                        sql += " boolean ";
                    }
                }
                logger.info("execute alter:" + sql);
                stmt = conn.createStatement();
                stmt.executeUpdate(sql);
                JdbcUtils.close(stmt);
            }
        }
        JdbcUtils.close(pstmt);
        conn.commit();
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(stmt);
        JdbcUtils.close(pstmt);
        JdbcUtils.close(conn);
    }
}

From source file:com.glaf.dts.transform.MxTransformManager.java

@SuppressWarnings("unchecked")
protected List<Map<String, Object>> prepare(QueryDefinition query, Map<String, Object> paramMap) {
    logger.debug("-------------------------2 start------------------------");
    List<Map<String, Object>> resultList = new java.util.ArrayList<Map<String, Object>>();

    Connection conn = null;/*from   w w w .  jav a  2 s.  com*/
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        Database database = databaseService.getDatabaseById(query.getDatabaseId());
        if (database != null) {
            conn = DBConnectionFactory.getConnection(database.getName());
        } else {
            conn = DBConnectionFactory.getConnection();
        }
        logger.debug("-------------------------2 connection------------------------");
        SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(query.getSql(), paramMap);
        logger.debug("--2 sql:" + sqlExecutor.getSql());
        psmt = conn.prepareStatement(sqlExecutor.getSql());
        if (sqlExecutor.getParameter() != null) {
            List<Object> values = (List<Object>) sqlExecutor.getParameter();
            JdbcUtils.fillStatement(psmt, values);
        }

        rs = psmt.executeQuery();
        logger.debug("-------------------------2 executeQuery------------------------");
        rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        while (rs.next()) {
            Map<String, Object> rowMap = new java.util.HashMap<String, Object>();
            for (int i = 1; i <= count; i++) {
                String columnName = rsmd.getColumnLabel(i);
                if (null == columnName || 0 == columnName.length()) {
                    columnName = rsmd.getColumnName(i);
                }
                try {
                    rowMap.put(columnName, rs.getObject(i));
                } catch (SQLException ex) {
                    rowMap.put(columnName, rs.getString(i));
                }
            }
            resultList.add(rowMap);
        }

        query.setResultList(resultList);

        // logger.debug("resultList:" + resultList);

        return resultList;
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(psmt);
        JdbcUtils.close(conn);
        logger.debug("-------------------------2 end------------------------");
    }
}

From source file:com.feedzai.commons.sql.abstraction.engine.AbstractDatabaseEngine.java

/**
 * Gets the query metadata./* www .j  a v  a 2s  .co m*/
 *
 * @param query The query to retrieve the metadata from.
 * @return A representation of the table columns and types.
 * @throws DatabaseEngineException If something occurs getting the metadata.
 */
@Override
public Map<String, DbColumnType> getQueryMetadata(String query) throws DatabaseEngineException {
    final Map<String, DbColumnType> metaMap = new LinkedHashMap<String, DbColumnType>();
    ResultSet rs = null;
    Statement stmt = null;

    try {
        getConnection();
        stmt = conn.createStatement();
        long start = System.currentTimeMillis();
        rs = stmt.executeQuery(query);
        logger.trace("[{} ms] {}", (System.currentTimeMillis() - start), query);

        ResultSetMetaData meta = rs.getMetaData();
        for (int i = 1; i <= meta.getColumnCount(); i++) {
            metaMap.put(meta.getColumnName(i), toPdbType(meta.getColumnType(i)));
        }

        stmt.close();

        return metaMap;
    } catch (final Exception e) {
        throw new DatabaseEngineException("Error querying", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception e) {
            logger.trace("Error closing result set.", e);
        }

        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (Exception e) {
            logger.trace("Error closing statement.", e);
        }
    }
}

From source file:org.cloudgraph.rdb.filter.RDBStatementExecutor.java

@Override
public List<PropertyPair> executeInsertWithGeneratedKeys(PlasmaType type, StringBuilder sql,
        Map<String, PropertyPair> values) {
    List<PropertyPair> resultKeys = new ArrayList<PropertyPair>();
    PreparedStatement statement = null;
    List<InputStream> streams = null;
    ResultSet generatedKeys = null;
    try {//  w  w  w. jav a  2 s  .  c  o m

        if (log.isDebugEnabled()) {
            log.debug("execute: " + sql.toString());
            StringBuilder paramBuf = createParamDebug(values);
            log.debug("params: " + paramBuf.toString());
        }

        statement = con.prepareStatement(sql.toString(), PreparedStatement.RETURN_GENERATED_KEYS);

        for (PropertyPair pair : values.values()) {
            PlasmaProperty valueProp = pair.getProp();
            if (pair.getValueProp() != null)
                valueProp = pair.getValueProp();
            int jdbcType = converter.toJDBCDataType(valueProp, pair.getValue());
            Object jdbcValue = converter.toJDBCDataValue(valueProp, pair.getValue());
            if (jdbcType != Types.BLOB && jdbcType != Types.VARBINARY) {
                statement.setObject(pair.getColumn(), jdbcValue, jdbcType);
            } else {
                byte[] bytes = (byte[]) jdbcValue;
                long len = bytes.length;
                ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                statement.setBinaryStream(pair.getColumn(), is, len);
                if (streams == null)
                    streams = new ArrayList<InputStream>();
                streams.add(is);
            }
        }

        statement.execute();
        generatedKeys = statement.getGeneratedKeys();
        ResultSetMetaData rsMeta = generatedKeys.getMetaData();
        int numcols = rsMeta.getColumnCount();
        if (log.isDebugEnabled())
            log.debug("returned " + numcols + " keys");

        if (generatedKeys.next()) {
            // FIXME; without metadata describing which properties
            // are actually a sequence, there is guess work
            // involved in matching the values returned
            // automatically from PreparedStatment as they
            // are anonymous in terms of the column names
            // making it impossible to match them to a metadata
            // property.
            List<Property> pkPropList = type.findProperties(KeyType.primary);
            if (pkPropList == null || pkPropList.size() == 0)
                throw new DataAccessException("no pri-key properties found for type '" + type.getName() + "'");
            if (pkPropList.size() > 1)
                throw new DataAccessException("multiple pri-key properties found for type '" + type.getName()
                        + "' - cannot map to generated keys");
            PlasmaProperty prop = (PlasmaProperty) pkPropList.get(0);
            // FIXME: need to find properties per column by physical name
            // alias
            // in case where multiple generated pri-keys
            for (int i = 1; i <= numcols; i++) {
                String columnName = rsMeta.getColumnName(i);
                if (log.isDebugEnabled())
                    log.debug("returned key column '" + columnName + "'");
                int columnType = rsMeta.getColumnType(i);
                Object value = converter.fromJDBCDataType(generatedKeys, i, columnType, prop);
                PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value);
                resultKeys.add(pair);
            }
        }
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        if (streams != null)
            try {
                for (InputStream stream : streams)
                    stream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
    }

    return resultKeys;
}