Example usage for java.sql ResultSet getMetaData

List of usage examples for java.sql ResultSet getMetaData

Introduction

In this page you can find the example usage for java.sql ResultSet getMetaData.

Prototype

ResultSetMetaData getMetaData() throws SQLException;

Source Link

Document

Retrieves the number, types and properties of this ResultSet object's columns.

Usage

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

@Test
public void testTables() throws SQLException {
    CassandraStatement statement = (CassandraStatement) con.createStatement();
    ResultSet result = MetadataResultSets.makeTables(statement, null, null);

    System.out.println("--- testTables() ---");
    System.out.println(getColumnNames(result.getMetaData()));

    System.out.println(toString(result));
    System.out.println();/*from   w  w w  .j  av a  2s  . co  m*/

    result = MetadataResultSets.makeTables(statement, KEYSPACE2, null);
    System.out.println(toString(result));
    System.out.println();

    result = MetadataResultSets.makeTables(statement, null, "test1");
    System.out.println(toString(result));
    System.out.println();

    result = MetadataResultSets.makeTables(statement, KEYSPACE2, "test1");
    System.out.println(toString(result));
    System.out.println();
}

From source file:com.netspective.axiom.sql.ResultSetUtils.java

public Map getResultSetSingleRowAsMap(ResultSet rs, boolean useLabelAsKey) throws SQLException {
    Map result = new HashMap();
    if (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colsCount = rsmd.getColumnCount();
        for (int i = 1; i <= colsCount; i++) {
            result.put(/*from   w  w  w .jav a  2s . c  om*/
                    useLabelAsKey ? rsmd.getColumnLabel(i).toLowerCase() : rsmd.getColumnName(i).toLowerCase(),
                    rs.getObject(i));
        }
        return result;
    } else
        return null;
}

From source file:teambootje.A6.java

/**
 * Creates new form A6//  www.  ja  va 2 s . co m
 */
public A6() {
    initComponents();
    setLocationRelativeTo(null);
    setLayout(new BorderLayout());

    //Create and set up the window.
    setTitle("SS Rotterdam Analyse || Analyse 6");
    ImageIcon icon = new ImageIcon("img/bootje.jpg");
    setIconImage(icon.getImage());

    // back BTN
    JButton back = new JButton("Back");
    add(back, BorderLayout.NORTH);

    back.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            dispose();
            //   throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

    // panel en Label
    JPanel ana = new JPanel();
    add(ana, BorderLayout.CENTER);

    //tabel
    String sql = "SELECT Locatie.land, locatie.stad, count(persoon.LID) as Aantal FROM persoon, Locatie WHERE persoon.LID = locatie.LID GROUP BY stad";
    List<Object[]> list = new ArrayList<Object[]>();
    ResultSet rs = null;
    try {
        rs = db.runSql(sql);
        while (rs.next()) {
            String city = rs.getString("locatie.stad");
            int amount = rs.getInt("Aantal");
            String[] row = new String[rs.getMetaData().getColumnCount()];
            for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                row[i - 1] = rs.getString(i);
            }
            list.add(row);

            //chart
            JButton chart = new JButton("Chart");
            add(chart, BorderLayout.SOUTH);

            chart.addActionListener(new ActionListener() {
                String c1 = city;
                int a1 = amount;

                @Override
                public void actionPerformed(ActionEvent e) {
                    DefaultPieDataset pieDataset = new DefaultPieDataset();
                    pieDataset.setValue(c1, a1);
                    pieDataset.setValue("Rotterdam", new Integer(1));
                    pieDataset.setValue("Bergen op zoom", new Integer(1));

                    JFreeChart chart = ChartFactory.createPieChart3D("Waar komen bezoekers vandaan", pieDataset,
                            true, true, true);
                    PiePlot3D p = (PiePlot3D) chart.getPlot();
                    //p.setForegroundAlpha(TOP_ALIGNMENT);
                    ChartFrame pie = new ChartFrame("Waar komen bezoekers vandaan", chart);
                    pie.setVisible(true);
                    pie.setSize(500, 500);
                    pie.setLocationRelativeTo(null);

                    //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                }
            });
        }
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e);
    }

    Object[][] array = new Object[list.size()][];
    Object columnNames[] = { "Land", "stad", "Aantal" };
    list.toArray(array);

    JTable table = new JTable(array, columnNames);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize(new Dimension(400, 400));
    ana.add(scroll);
}

From source file:esavo.tap.formatter.ResultSet2JsonFormatter.java

@Override
protected DBColumn[] writeMetadata(UwsJob job, ResultSet queryResult, JSONWriter out,
        TAPExecutionReport execReport) throws IOException, TAPException, InterruptedException, JSONException {
    out.array();//from   ww w.j  ava  2  s  . c  o  m
    DBColumn[] selectedColumns = execReport.resultingColumns;

    try {
        ResultSetMetaData meta = queryResult.getMetaData();
        int indField = 1;
        if (selectedColumns != null) {
            for (DBColumn field : selectedColumns) {
                if (job.isPhaseAborted()) {
                    return selectedColumns;
                }
                TAPColumn tapCol = null;
                try {
                    tapCol = (TAPColumn) field;
                } catch (ClassCastException ex) {
                    tapCol = new TAPColumn(field.getADQLName());
                    tapCol.setDatatype(meta.getColumnTypeName(indField), TAPTypes.NO_SIZE);
                    service.getFactory().getLogger()
                            .warning("Unknown DB datatype for the field \"" + tapCol.getName()
                                    + "\" ! It is supposed to be \"" + tapCol.getDatatype()
                                    + "\" (original value: \"" + meta.getColumnTypeName(indField) + "\").");
                    selectedColumns[indField - 1] = tapCol;
                }
                writeFieldMeta(tapCol, out);
                indField++;

                //               if (thread.isInterrupted())
                //                  throw new InterruptedException();
            }
        }
    } catch (SQLException e) {
        service.getFactory().getLogger().error(
                "Job N" + execReport.jobID + " - Impossible to get the metadata of the given ResultSet !", e);
    }

    out.endArray();
    return selectedColumns;
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.CDCJdbcRunnable.java

@Override
public void generateSchemaChanges(BatchContext batchContext) throws SQLException {
    Map<String, Integer> source = new HashMap<>();
    ResultSet rs = tableReadContext.getMoreResultSet();
    String schemaName = "";
    String tableName = "";
    String captureInstanceName = "";

    if (rs != null && rs.next()) {
        ResultSetMetaData data = rs.getMetaData();

        for (int i = 1; i <= data.getColumnCount(); i++) {
            String label = data.getColumnLabel(i);
            if (label.equals(MSQueryUtil.CDC_SOURCE_SCHEMA_NAME)) {
                schemaName = rs.getString(label);
            } else if (label.equals(MSQueryUtil.CDC_SOURCE_TABLE_NAME)) {
                tableName = rs.getString(label);
            } else if (label.equals(MSQueryUtil.CDC_CAPTURE_INSTANCE_NAME)) {
                captureInstanceName = rs.getString(label);
            } else {
                int type = data.getColumnType(i);
                source.put(label, type);
            }//from w ww .  j a va  2s.c o  m
        }

        boolean schemaChanges = getDiff(captureInstanceName, source,
                tableRuntimeContext.getSourceTableContext().getColumnToType());

        if (schemaChanges) {
            JdbcEvents.SCHEMA_CHANGE.create(context, batchContext).with("source-table-schema-name", schemaName)
                    .with("source-table-name", tableName).with("capture-instance-name", captureInstanceName)
                    .createAndSend();
            context.processBatch(batchContext);
        }
    }
}

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

@Test
public void testColumns() throws SQLException, CharacterCodingException {

    CassandraStatement statement = (CassandraStatement) con.createStatement();
    ResultSet result = MetadataResultSets.makeColumns(statement, KEYSPACE1, "test1", null);

    System.out.println("--- testColumns() ---");
    System.out.println(getColumnNames(result.getMetaData()));

    System.out.println(toString(result));
    System.out.println();/*  w w  w  . j av  a2  s.  c o  m*/

    result = MetadataResultSets.makeColumns(statement, KEYSPACE1, "test2", null);

    System.out.println("--- testColumns() ---");
    System.out.println(getColumnNames(result.getMetaData()));

    System.out.println(toString(result));
    System.out.println();
}

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

@Test
public void testClob() throws SQLException, CharacterCodingException {

    CassandraStatement statement = (CassandraStatement) con.createStatement();
    ResultSet result = MetadataResultSets.makeColumns(statement, KEYSPACE1, "test3", null);

    System.out.println("--- testColumns() ---");
    System.out.println(getColumnNames(result.getMetaData()));

    System.out.println(toString(result));
    System.out.println();//from   ww  w  . jav a  2s .  c  o  m

    result = MetadataResultSets.makeColumns(statement, KEYSPACE1, "test3", null);

    System.out.println("--- testColumns() ---");
    System.out.println(getColumnNames(result.getMetaData()));

    System.out.println(toString(result));
    System.out.println();
}

From source file:org.gsoft.admin.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in/*from  w  ww  .j  av a2  s.  c o  m*/
 * 
 * @param conn
 *            - the connection to use for the script
 * @param reader
 *            - the source of the script
 * @throws SQLException
 *             if any SQL errors occur
 * @throws IOException
 *             if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                println(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                println(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        printlnError("Error executing: " + command);
                        printlnError(e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        print(name + "\t");
                    }
                    println("");
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            print(value + "\t");
                        }
                        println("");
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } finally {
        conn.rollback();
        flush();
    }
}

From source file:esg.gateway.service.ESGAccessLogServiceImpl.java

/**
   Initializes the service by setting up the database connection and result handling.
*//*  ww  w.j  av a2  s  . co m*/
public void init() {
    Properties props = new Properties();
    props.setProperty("db.protocol", "jdbc:postgresql:");
    props.setProperty("db.host", "localhost");
    props.setProperty("db.port", "5432");
    props.setProperty("db.database", "esgcet");
    props.setProperty("db.user", "dbsuper");
    props.setProperty("db.password", "changeme");
    try {
        props.putAll(new ESGFProperties());
    } catch (IOException ex) {
        log.error(ex);
    }

    queryRunner = new QueryRunner(DatabaseResource.init(props.getProperty("db.driver", "org.postgresql.Driver"))
            .setupDataSource(props).getDataSource());

    resultSetHandler = new ResultSetHandler<List<String[]>>() {
        public List<String[]> handle(ResultSet rs) throws SQLException {
            ArrayList<String[]> results = new ArrayList<String[]>();
            String[] record = null;
            assert (null != results);

            ResultSetMetaData meta = rs.getMetaData();
            int cols = meta.getColumnCount();
            log.trace("Number of fields: " + cols);

            log.trace("adding column data...");
            record = new String[cols];
            for (int i = 0; i < cols; i++) {
                try {
                    record[i] = meta.getColumnLabel(i + 1) + "|" + meta.getColumnType(i + 1);
                } catch (SQLException e) {
                    log.error(e);
                }
            }
            results.add(record);

            for (int i = 0; rs.next(); i++) {
                log.trace("Looking at record " + (i + 1));
                record = new String[cols];
                for (int j = 0; j < cols; j++) {
                    record[j] = rs.getString(j + 1);
                    log.trace("gathering result record column " + (j + 1) + " -> " + record[j]);
                }
                log.trace("adding record ");
                results.add(record);
                record = null; //gc courtesy
            }
            return results;
        }
    };
    log.trace("initialization complete");
}

From source file:teambootje.A7.java

/**
 * Creates new form A7/*w ww  .j  a  v  a2s.  c o m*/
 */
public A7() {
    initComponents();
    setLocationRelativeTo(null);
    setLayout(new BorderLayout());

    //Create and set up the window.
    setTitle("SS Rotterdam Analyse || Analyse 7");
    ImageIcon icon = new ImageIcon("img/bootje.jpg");
    setIconImage(icon.getImage());

    // back BTN
    JButton back = new JButton("Back");
    add(back, BorderLayout.NORTH);

    back.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            dispose();
            //    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

    // panel en Label
    JPanel ana = new JPanel();
    add(ana, BorderLayout.CENTER);

    //tabel
    String sql = "SELECT doelgroep.doelgroep, COUNT(*) AS Aantal FROM doelgroep GROUP BY doelgroep.doelgroep";
    List<Object[]> list = new ArrayList<Object[]>();
    ResultSet rs = null;
    try {
        rs = db.runSql(sql);
        while (rs.next()) {
            String ta = rs.getString("doelgroep.Doelgroep");
            int amount = rs.getInt("Aantal");
            String[] row = new String[rs.getMetaData().getColumnCount()];
            for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                row[i - 1] = rs.getString(i);
            }
            list.add(row);

            //chart
            JButton chart = new JButton("Chart");
            add(chart, BorderLayout.SOUTH);

            chart.addActionListener(new ActionListener() {
                String dd = ta;
                int a1 = amount;

                @Override
                public void actionPerformed(ActionEvent e) {

                    DefaultPieDataset pieDataset = new DefaultPieDataset();
                    pieDataset.setValue(dd, a1);
                    pieDataset.setValue("Bedrijfsleven", new Integer(1));
                    pieDataset.setValue("50+", new Integer(1));
                    pieDataset.setValue("40+", new Integer(1));
                    pieDataset.setValue("30+", new Integer(1));
                    JFreeChart chart = ChartFactory.createPieChart3D("Aantal mensen per Doelgroep", pieDataset,
                            true, true, true);
                    PiePlot3D p = (PiePlot3D) chart.getPlot();
                    //p.setForegroundAlpha(TOP_ALIGNMENT);
                    ChartFrame pie = new ChartFrame("Aantal mensen per Doelgroep", chart);
                    pie.setVisible(true);
                    pie.setSize(500, 500);
                    pie.setLocationRelativeTo(null);

                    //    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                }
            });
        }
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e);
    }

    Object[][] array = new Object[list.size()][];
    Object columnNames[] = { "Doelgroep", "Aantal" };
    list.toArray(array);

    JTable table = new JTable(array, columnNames);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize(new Dimension(400, 400));
    ana.add(scroll);

}