예제 #1
1
 private String getInfo(ResultSet rs) throws SQLException {
   // position to first record
   boolean moreRecords = rs.next();
   // If there are no records, display a message
   if (!moreRecords) {
     return null;
   }
   Vector columnHeads = new Vector();
   Vector rows = new Vector();
   try {
     // get column heads
     ResultSetMetaData rsmd = rs.getMetaData();
     for (int i = 1; i <= rsmd.getColumnCount(); ++i)
       columnHeads.addElement(rsmd.getColumnName(i));
     // get row data
     do {
       rows.addElement(getNextRow(rs, rsmd));
     } while (rs.next());
     String info;
     String aux = rows.get(0).toString();
     info = aux.substring(1, aux.length() - 1);
     return info;
   } catch (SQLException sqlex) {
     sqlex.printStackTrace();
     return null;
   }
 }
예제 #2
0
 protected void executeQuery(Statement stmt, String q) throws SQLException {
   q = q.replace("$PREFIX", getPrefix());
   LOG.info(" Executing " + q);
   ResultSet rs = stmt.executeQuery(q);
   StringBuilder header = new StringBuilder();
   for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
     if (i > 1) {
       header.append("|");
     }
     header.append(rs.getMetaData().getColumnName(i));
   }
   LOG.info(header);
   int seq = 0;
   while (true) {
     boolean valid = rs.next();
     if (!valid) break;
     seq++;
     StringBuilder line = new StringBuilder();
     for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
       if (i > 1) {
         line.append("|");
       }
       line.append(rs.getString(i));
     }
     LOG.info(seq + ":" + line);
   }
 }
 public ResultSetMetaData getColumnsByFetch(String tableNamePattern, Connection connection)
     throws SQLException {
   String query = "select * from " + tableNamePattern + " where 1 = 0";
   Statement createStatement = connection.createStatement();
   ResultSet rs = createStatement.executeQuery(query);
   int columnCount = rs.getMetaData().getColumnCount();
   return rs.getMetaData();
 }
 public ActionForward execute(
     ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res)
     throws Exception {
   ServiceDataForm obj = (ServiceDataForm) form;
   String serviceId = obj.getServiceId();
   CalculateService obj2 = new CalculateService();
   obj2.calculate(serviceId);
   Connection con = null;
   Class.forName(ConnectionStats.DRIVER);
   String url = ConnectionStats.DB_URL;
   String usr = ConnectionStats.DB_USER;
   String pwd = ConnectionStats.DB_PASSWORD;
   con = DriverManager.getConnection(url, usr, pwd);
   Statement stmt = con.createStatement();
   ResultSet rs = null;
   rs = stmt.executeQuery("select * from " + serviceId + "_main");
   ResultSetMetaData rsmd = rs.getMetaData();
   int col = rsmd.getColumnCount();
   String[] mainHeader = new String[col];
   for (int i = 0; i < col; i++) {
     mainHeader[i] = rsmd.getColumnLabel(i + 1);
   }
   ArrayList<String[]> serviceDataMain = new ArrayList<String[]>();
   while (rs.next()) {
     String[] str = new String[col];
     for (int i = 0; i < col; i++) {
       str[i] = rs.getString(i + 1);
     }
     serviceDataMain.add(str);
   }
   req.setAttribute("mainHeader", mainHeader);
   req.setAttribute("serviceDataMain", serviceDataMain);
   rs = stmt.executeQuery("select * from " + serviceId + "_tbl");
   rsmd = rs.getMetaData();
   col = rsmd.getColumnCount();
   String[] tblHeader = new String[col];
   for (int i = 0; i < col; i++) {
     tblHeader[i] = rsmd.getColumnLabel(i + 1);
   }
   ArrayList<String[]> serviceDatatbl = new ArrayList<String[]>();
   while (rs.next()) {
     String[] str = new String[col];
     for (int i = 0; i < col; i++) {
       str[i] = rs.getString(i + 1);
     }
     serviceDatatbl.add(str);
   }
   req.setAttribute("tblHeader", tblHeader);
   req.setAttribute("serviceDatatbl", serviceDatatbl);
   rs.close();
   con.close();
   return mapping.findForward("success");
 }
예제 #5
0
  // Vertaa kahta ResultSettiä.
  public boolean vertaaTulokset(ResultSet rs, ResultSet esim) {

    String tulos = "";
    String vastaus = "";
    boolean palautus = true;

    // Tarkistetaan ettei kumpikaan parametri ole tyhjä
    if (rs == null | esim == null) {
      return false;
    }

    try {
      // Hankitaan tietoja resultSeteistä.
      ResultSetMetaData rsMeta = rs.getMetaData();
      ResultSetMetaData esimMeta = esim.getMetaData();

      int rsColumnit = rsMeta.getColumnCount();
      int esimColumnit = esimMeta.getColumnCount();

      String kokovastaus = "";
      String kokotulos = "";

      // Jatketaan kunnes molemmat setit loppuvat
      System.out.println("\nOikean vastauksen tuottama tulos:");
      while (esim.next()) {
        for (int i = 1; i <= esimColumnit; i++) {
          vastaus = esim.getString(i);
          System.out.println(vastaus);
          kokovastaus += vastaus;
        }
      }
      System.out.println("\nVastauksesi tuottama tulos:");
      while (rs.next()) {
        for (int i = 1; i <= rsColumnit; i++) {
          tulos = rs.getString(i);
          System.out.println(tulos);
          kokotulos += tulos;
        }
      }
      if (!kokovastaus.equals(kokotulos)) {
        palautus = false;
      }

      return palautus;

    } catch (SQLException e) {
      System.out.println("Tulosten vertauksessa tapahtui seuraava virhe: " + e.getMessage());
      e.printStackTrace();
      return false;
    }
  }
예제 #6
0
  private void jTbdescripcionKeyPressed(
      java.awt.event.KeyEvent evt) { // GEN-FIRST:event_jTbdescripcionKeyPressed

    try {
      // se comienza la conexion con la base de datos
      try {
        con = new Conexion();

      } catch (ClassNotFoundException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SQLException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      }

      String nom = jTbdescripcion.getText();
      String sql = "SELECT * FROM productos WHERE nombre_producto LIKE '" + nom + "%'";
      rs = con.Consulta(sql);

      if (rs == null)
        JOptionPane.showMessageDialog(
            null, "No se encontro: " + jTbdescripcion.getText() + " en la base de datos.");

      // Para establecer el modelo al JTable

      DefaultTableModel buscar =
          new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int rowIndex, int vColIndex) {
              return false;
            }
          };
      this.jTbuscar.setModel(buscar);

      // Obteniendo la informacion de las columnas que estan siendo consultadas
      ResultSetMetaData rsMd = rs.getMetaData();
      // La cantidad de columnas que tiene la consulta
      int cantidadColumnas = rsMd.getColumnCount();
      // Establecer como cabezeras el nombre de las colimnas
      for (int i = 1; i <= cantidadColumnas; i++) {
        buscar.addColumn(rsMd.getColumnLabel(i));
      }

      while (rs.next()) {
        Object[] fila = new Object[cantidadColumnas];

        for (int i = 0; i < cantidadColumnas; i++) {

          fila[i] = rs.getObject(i + 1);
        }
        buscar.addRow(fila);
      }

    } catch (SQLException ex) {
      Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
    }
  } // GEN-LAST:event_jTbdescripcionKeyPressed
  private Table createTable(Connection conn, ResultSet rs) throws SQLException {
    String realTableName = null;
    try {
      ResultSetMetaData rsMetaData = rs.getMetaData();
      String schemaName = rs.getString("TABLE_SCHEM") == null ? "" : rs.getString("TABLE_SCHEM");
      realTableName = rs.getString("TABLE_NAME");
      String tableType = rs.getString("TABLE_TYPE");
      String remarks = rs.getString("REMARKS");
      if (remarks == null && dbHelper.isOracleDataBase()) {
        remarks = getOracleTableComments(realTableName);
      }

      Table table = new Table();
      table.setSqlName(realTableName);
      table.setRemarks(remarks);

      if ("SYNONYM".equals(tableType) && dbHelper.isOracleDataBase()) {
        table.setOwnerSynonymName(getSynonymOwner(realTableName));
      }

      retriveTableColumns(table);

      table.initExportedKeys(conn.getMetaData());
      table.initImportedKeys(conn.getMetaData());
      BeanHelper.copyProperties(
          table, TableOverrideValuesProvider.getTableOverrideValues(table.getSqlName()));
      return table;
    } catch (SQLException e) {
      throw new RuntimeException("create table object error,tableName:" + realTableName, e);
    }
  }
예제 #8
0
 /**
  * Affiche le resultSet en System.out (utile pour le DEBUG)
  *
  * @param rs ResultSet à afficher
  */
 public void print_resultSet(ResultSet rs) {
   if (rs != null) {
     ResultSetMetaData md = null;
     int nombreColumns = 0;
     try {
       md = rs.getMetaData();
       nombreColumns = md.getColumnCount();
       String[] nomColumns = new String[nombreColumns];
       for (int i = 1; i < (nombreColumns + 1); i++) {
         nomColumns[i - 1] = md.getColumnName(i);
       }
       int i = 1;
       while (rs.next()) {
         System.out.print("DEBUG : Row " + i + " : ");
         for (String s : nomColumns) {
           System.out.print(rs.getString(s) + " ");
         }
         i++;
         System.out.println();
       }
       rs.beforeFirst();
     } catch (SQLException ex) {
       Logger.getLogger(Request_MySQL.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
 }
예제 #9
0
파일: bdeDb.java 프로젝트: Twistleton/rb
  public String getHtmlSelectAllg(String iName, String iSql, String iOption) {
    Statement stmt;
    ResultSet rs;
    ResultSetMetaData rsmd;
    String retString = new String();

    retString = "\n<SELECT NAME=\"" + iName + "\">";
    retString += iOption;
    try {
      stmt = bdeConnection.createStatement();
      stmt.executeQuery(iSql);
      rs = stmt.getResultSet();
      rsmd = rs.getMetaData();
      while (rs.next()) {
        // Der Wert des Auswahlfeldes wird durch das Letzte Feld des Selektierten Datensatzes
        // bestimmt
        retString += "\n<OPTION VALUE=\"" + rs.getString(rsmd.getColumnCount()) + "\">";
        // Alle Felder bis auf das Letzte werden im Auswahlfeld angezeigt...
        for (int lauf = 1; lauf < rsmd.getColumnCount(); lauf++) {
          retString += rs.getString(lauf) + " ";
        }
      }
      rs.close();
      stmt.close();
    } catch (SQLException sqlEx) {
      sqlEx.printStackTrace();
      retString += "<OPTION> Methode getHtmlSelectAllg: Fehler beim Datenbankzugriff";
    }
    retString += "</SELECT>\n";
    return retString;
  }
예제 #10
0
  public static void fillTable(String aQuery, JTable aTable, Connector aConnector)
      throws SQLException {
    ((DefaultTableModel) aTable.getModel()).setRowCount(0);
    ((DefaultTableModel) aTable.getModel()).setColumnCount(0);

    ResultSet results = aConnector.sendQuery(aQuery);
    ResultSetMetaData metadata = results.getMetaData();

    cols = metadata.getColumnCount();

    rowData = new Object[cols];
    colNames = new String[cols];

    for (int i = 0; i < cols; i++) {
      colNames[i] = metadata.getColumnName(i + 1);
    }
    for (int i = 0; i < cols; i++) {
      ((DefaultTableModel) aTable.getModel()).addColumn(colNames[i]);
    }

    while (results.next()) {
      for (int i = 0; i < cols; i++) {
        if (metadata.getColumnName(i + 1).equalsIgnoreCase("DatePosted")) {
          rowData[i] = StrVal.SqlStringToString(results.getDate(i + 1).toString());
          rowData[i] += " || ";
          rowData[i] += results.getTime(i + 1).toString();
        } else rowData[i] = results.getString(i + 1);
      }
      ((DefaultTableModel) aTable.getModel()).addRow(rowData);
    }
  }
예제 #11
0
 /**
  * Asserts that we find the expected values in the result set. We don't know the order, since we
  * don't always have an order by and we're going through indexes, but we assert that each expected
  * result occurs once as expected (in any order).
  */
 public static void assertValuesEqualsResultSet(ResultSet rs, List<List<Object>> expectedResults)
     throws SQLException {
   int expectedCount = expectedResults.size();
   int count = 0;
   List<List<Object>> actualResults = Lists.newArrayList();
   List<Object> errorResult = null;
   while (rs.next() && errorResult == null) {
     List<Object> result = Lists.newArrayList();
     for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
       result.add(rs.getObject(i + 1));
     }
     if (!expectedResults.contains(result)) {
       errorResult = result;
     }
     actualResults.add(result);
     count++;
   }
   assertTrue(
       "Could not find "
           + errorResult
           + " in expected results: "
           + expectedResults
           + " with actual results: "
           + actualResults,
       errorResult == null);
   assertEquals(expectedCount, count);
 }
예제 #12
0
 public Insert(java.awt.Frame parent, boolean modal, Connection cn, String h) {
   super(parent, modal);
   initComponents();
   con = cn;
   jPanel1.setBounds(0, 0, 800, 1000);
   s = h;
   try {
     Statement st = con.createStatement();
     ResultSet rs1 = st.executeQuery("select * from " + s);
     ResultSetMetaData rd = rs1.getMetaData();
     count = rd.getColumnCount();
     if (count >= 5) jPanel1.setLayout(new java.awt.GridLayout(count, 5, 20, 20));
     else jPanel1.setLayout(new java.awt.GridLayout(count, 5, 40, 40));
     l = new JLabel[count];
     l2 = new JLabel[count];
     l1 = new JLabel[count];
     t = new JTextField[count];
     jLabel1.setText("INSERT INTO " + s);
     getContentPane().add(jLabel1, BorderLayout.NORTH);
     for (i = 1; i <= count; i++) {
       if (rd.isNullable(i) == ResultSetMetaData.columnNoNulls) l2[i - 1] = new JLabel("Not Null");
       else l2[i - 1] = new JLabel("Nullable");
       l[i - 1] = new JLabel(rd.getColumnName(i));
       jPanel1.add(l[i - 1]);
       l1[i - 1] = new JLabel("(" + rd.getColumnTypeName(i) + ")");
       jPanel1.add(l1[i - 1]);
       jPanel1.add(l2[i - 1]);
       t[i - 1] = new JTextField();
       jPanel1.add(t[i - 1]);
     }
   } catch (Exception e) {
     System.out.println(e);
   }
 }
예제 #13
0
파일: MBeanUtil.java 프로젝트: Jach/luciddb
  public static String printView(ResultSet rs) throws Exception {
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int numCols = rsMetaData.getColumnCount();
    String[] headers = new String[numCols];
    OpenType[] allTypes = new OpenType[numCols];
    Vector[] values = new Vector[numCols];
    Object[] allValues = new Object[numCols];

    String ret = "";

    for (int i = 0; i < numCols; i++) {
      if (i == 0) {
        ret = rsMetaData.getColumnName(i + 1);
      } else {
        ret = ret + "," + rsMetaData.getColumnName(i + 1);
      }
    }
    ret = ret + "\n";

    while (rs.next()) {
      for (int i = 0; i < numCols; i++) {
        if (i == 0) {
          ret = ret + rs.getString(i + 1);
        } else {
          ret = ret + ", " + rs.getString(i + 1);
        }
      }
      ret = ret + "\n";
    }

    return ret;
  }
예제 #14
0
파일: MBeanUtil.java 프로젝트: Jach/luciddb
  public static TabularData createTable(ResultSet rs) throws Exception {
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int numCols = rsMetaData.getColumnCount();
    String[] headers = new String[numCols];
    OpenType[] allTypes = new OpenType[numCols];
    Vector[] values = new Vector[numCols];
    Object[] allValues = new Object[numCols];

    for (int i = 0; i < numCols; i++) {
      headers[i] = rsMetaData.getColumnName(i + 1);
      allTypes[i] = new ArrayType(1, SimpleType.STRING);
      values[i] = new Vector();
    }

    CompositeType ct =
        new CompositeType("column and values", "column and values", headers, headers, allTypes);
    TabularType tt = new TabularType("column and values", "column with values", ct, headers);
    TabularData td = new TabularDataSupport(tt);

    while (rs.next()) {
      for (int i = 0; i < numCols; i++) {
        values[i].add(rs.getString(i + 1));
      }
    }

    for (int i = 0; i < numCols; i++) {
      allValues[i] = (String[]) values[i].toArray(new String[0]);
    }

    CompositeData entry = new CompositeDataSupport(ct, headers, allValues);
    td.put(entry);
    return td;
  }
  // execute and get results
  private void execute(Connection conn, String text, Writer writer, boolean commaSeparator)
      throws SQLException {

    BufferedWriter buffer = new BufferedWriter(writer);
    Statement stmt = conn.createStatement();
    stmt.execute(text);
    ResultSet rs = stmt.getResultSet();
    ResultSetMetaData metadata = rs.getMetaData();
    int nbCols = metadata.getColumnCount();
    String[] labels = new String[nbCols];
    int[] colwidths = new int[nbCols];
    int[] colpos = new int[nbCols];
    int linewidth = 1;

    // read each occurrence
    try {
      while (rs.next()) {
        for (int i = 0; i < nbCols; i++) {
          Object value = rs.getObject(i + 1);
          if (value != null) {
            buffer.write(value.toString());
            if (commaSeparator) buffer.write(",");
          }
        }
      }
      buffer.flush();
      rs.close();
    } catch (IOException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      // ok, exit from the loop
    } catch (SQLException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
    }
  }
예제 #16
0
 public void actionPerformed(ActionEvent evt) {
   // 删除原来的JTable(JTable使用scrollPane来包装)
   if (scrollPane != null) {
     jf.remove(scrollPane);
   }
   try (
   // 根据用户输入的SQL执行查询
   ResultSet rs = stmt.executeQuery(sqlField.getText())) {
     // 取出ResultSet的MetaData
     ResultSetMetaData rsmd = rs.getMetaData();
     Vector<String> columnNames = new Vector<>();
     Vector<Vector<String>> data = new Vector<>();
     // 把ResultSet的所有列名添加到Vector里
     for (int i = 0; i < rsmd.getColumnCount(); i++) {
       columnNames.add(rsmd.getColumnName(i + 1));
     }
     // 把ResultSet的所有记录添加到Vector里
     while (rs.next()) {
       Vector<String> v = new Vector<>();
       for (int i = 0; i < rsmd.getColumnCount(); i++) {
         v.add(rs.getString(i + 1));
       }
       data.add(v);
     }
     // 创建新的JTable
     JTable table = new JTable(data, columnNames);
     scrollPane = new JScrollPane(table);
     // 添加新的Table
     jf.add(scrollPane);
     // 更新主窗口
     jf.validate();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  /**
   * Expand a single row to multiple rows. One row per column.
   *
   * @param sql
   * @param rs
   * @return
   * @throws SQLException
   */
  public static ResultList expandSqlResultSet(Sql sql, ResultSet rs) throws SQLException {
    ResultList resList = new ResultList();
    if (rs == null) return resList;
    ColumnDescriptor desc = new ColumnDescriptor();
    desc.addColumn("NAME", false, 1);
    desc.addColumn("VALUE", false, 2);
    resList.setColumnDescriptor(desc);

    java.sql.ResultSetMetaData meta = rs.getMetaData();
    int colCnt = meta.getColumnCount();

    int rowCnt = 0;
    while (rs
        .next()) // change to allow to expand multiple rows, with a row number separator and a row
    // count suffix
    {
      if (rowCnt > 0) {
        ResultRow row = new ResultRow();
        row.addColumn("--- ROW " + (rowCnt + 1) + "---");
        row.addColumn("");
        resList.addRow(row);
      }
      for (int i = 1; i <= colCnt; i++) {
        ResultRow row = new ResultRow();
        if (rowCnt > 0) row.addColumn(meta.getColumnName(i) + "(" + (rowCnt + 1) + ")");
        else row.addColumn(meta.getColumnName(i));

        row.addColumn(rs.getString(i));
        resList.addRow(row);
      }
      rowCnt++;
    }
    return resList;
  }
예제 #18
0
  /** Creates new form PrincipalCliente */
  public ModificarAdmin() {
    initComponents();
    conexioninicio ci = new conexioninicio();
    ci.conectar();
    this.setSize(470, 650);
    this.setLocationRelativeTo(null); // Centra la ventana Splash
    try {
      Connection con = DriverManager.getConnection(ci.getURl(), ci.getLogin(), ci.getPassword());
      //  System.out.println("Conexion a la base de datos cliente realizada con exito! ");
      Statement stmt = con.createStatement();

      ResultSet rs = stmt.executeQuery("SELECT * FROM tienda.estado ;");
      // obteniendo la informacion de las columnas que estan siendo consultadas
      ResultSetMetaData rsMd = rs.getMetaData();
      // La cantidad de columnas que tiene la consulta
      int cantidadColumnas = rsMd.getColumnCount();
      // Establecer como cabezeras el nombre de las columnas

      // Creando las filas para el Jtable
      while (rs.next()) {
        Object[] fila = new Object[cantidadColumnas];
        for (int i = 1; i < cantidadColumnas; i++) {
          jComboBox1.addItem(rs.getObject(i + 1));
        }
      }
      rs.close();
      con.close();

    } catch (Exception e) {

      JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
  }
예제 #19
0
  /** EJECUTA UNA CONSULTA Y GENERA LA TABLA HTML */
  protected String getHTML(String SQL) throws Exception {
    StringBuffer html = new StringBuffer();
    html.append("<TABLE border='1'>");
    html.append("<TR>");

    if (conectar()) {
      ResultSet rs = ejecutarSQL(SQL);
      ResultSetMetaData rsm = rs.getMetaData();
      html.append("<TR>");
      for (int i = 1; i <= rsm.getColumnCount(); i++) {
        html.append("<TH>" + rsm.getColumnName(i) + "</TH>");
      }
      html.append("</TR>");
      while (rs.next()) {
        html.append("<TR>");
        for (int i = 1; i <= rsm.getColumnCount(); i++) {
          html.append("<TD>" + rs.getString(i) + ".</TD>");
        }
        html.append("</TR>");
      }
      desconectar();
    }

    html.append("</TR>");
    html.append("</TABLE>");
    return html.toString();
  } // Fin getHTML
예제 #20
0
  // Tulostaa resultSetin
  public boolean tulostaRs(ResultSet rs) {

    if (rs != null) {

      try {

        ResultSetMetaData rsmd = rs.getMetaData();
        int columnit = rsmd.getColumnCount();

        while (rs.next()) {

          for (int i = 1; i <= columnit; i++) {
            if (i > 1) System.out.print("  |  ");
            System.out.print(rs.getString(i));
          }
          System.out.println("");
        }
        return true;
      } catch (SQLException e) {
        System.out.println("ResultSetin tulostuksessa tapahtui virhe: " + e.getMessage());
        e.printStackTrace();
        return false;
      }
    } else {
      System.out.println("VIRHE: tulosjoukko on tyhjä.");
      return false;
    }
  }
예제 #21
0
 public ObjectArrayRowBuilder(ResultSet resultSet, Primitive[] primitives, int[] types)
     throws SQLException {
   this.resultSet = resultSet;
   this.primitives = primitives;
   this.types = types;
   this.columnCount = resultSet.getMetaData().getColumnCount();
 }
예제 #22
0
  public static void duration() {
    connectDb();
    String sql = "select min(time), max(time), count(*) from " + tablename + ";";
    try {
      ResultSet rs = query.executeQuery(sql);
      rs.next();
      int numCols = rs.getMetaData().getColumnCount();
      String minTime = rs.getString(1);
      String maxTime = rs.getString(2);
      String numPackets = rs.getString(3);
      System.out.println(
          "Experiment "
              + tablename
              + "\n\tfrom: "
              + minTime
              + "\n\tto: "
              + maxTime
              + "\n\tpackets: "
              + numPackets);

    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e);
      System.exit(1);
    }
  }
예제 #23
0
  public void setQuery(String q) {
    cache = new Vector();
    try {
      ResultSet rs = statement.executeQuery(q);
      ResultSetMetaData meta = rs.getMetaData();
      colCount = meta.getColumnCount();
      headers = new String[colCount];
      for (int h = 1; h <= colCount; h++) {
        headers[h - 1] = meta.getColumnName(h);
      }
      while (rs.next()) {
        String[] record = new String[colCount];
        for (int i = 0; i < colCount; i++) {
          record[i] = rs.getString(i + 1);
        }
        cache.addElement(record);
      } // while sonu

      fireTableChanged(null);
    } // try sonu
    catch (Exception e) {
      cache = new Vector();
      e.printStackTrace();
    }
  } // setQuery sonu
  public static void populateTable() {
    System.out.println("started");
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    try {

      conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
      stmt = conn.prepareStatement("select * from class");

      rs = stmt.executeQuery();
      ResultSetMetaData metaData = rs.getMetaData();
      System.out.println("connected");

      Vector<String> columnNames = new Vector<String>(); // vector to store names of columns

      int columnCount = metaData.getColumnCount(); // get number of columns

      for (int i = 1; i <= columnCount; i++) {
        System.out.println("loop columnams.add");

        columnNames.add(metaData.getColumnName(i)); // adding column names in the vector
      }

      Vector<Vector<Object>> data = new Vector<Vector<Object>>();
      while (rs.next()) {
        System.out.println("while rs.next");

        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
          vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
      }
      System.out.println("done loop");

      DefaultTableModel temp = new DefaultTableModel(data, columnNames);

      //  JTable tablez = new JTable(temp);
      // System.out.println(tablez);

      table.setModel(temp);
      table.setModel(temp);

      // table = tablez;
      // System.out.println();

    } catch (SQLException e1) {

      e1.printStackTrace();
    }
  }
예제 #25
0
  /*
   * Execute query against a list of sensors
   *
   * */
  public static String executeQuery(
      String envelope, String query, String matchingSensors, String format) throws ParseException {

    // String matchingSensors = getListOfSensorsAsString(envelope);

    String reformattedQuery = reformatQuery(query, matchingSensors);
    StringBuilder sb = new StringBuilder();
    Connection connection = null;

    try {
      connection = Main.getDefaultStorage().getConnection();
      Statement statement =
          connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      ResultSet results = statement.executeQuery(reformattedQuery);
      ResultSetMetaData metaData; // Additional information about the results
      int numCols, numRows; // How many rows and columns in the table
      metaData = results.getMetaData(); // Get metadata on them
      numCols = metaData.getColumnCount(); // How many columns?
      results.last(); // Move to last row
      numRows = results.getRow(); // How many rows?

      String s;

      // System.out.println("* Executing query *\n" + reformattedQuery + "\n***");

      // headers
      // sb.append("# Query: " + query + NEWLINE);
      sb.append("# Query: " + reformattedQuery.replaceAll("\n", "\n# ") + NEWLINE);

      sb.append("# ");
      // System.out.println("ncols: " + numCols);
      // System.out.println("nrows: " + numRows);
      for (int col = 0; col < numCols; col++) {
        sb.append(metaData.getColumnLabel(col + 1));
        if (col < numCols - 1) sb.append(SEPARATOR);
      }
      sb.append(NEWLINE);

      for (int row = 0; row < numRows; row++) {
        results.absolute(row + 1); // Go to the specified row
        for (int col = 0; col < numCols; col++) {
          Object o = results.getObject(col + 1); // Get value of the column
          // logger.warn(row + " , "+col+" : "+ o.toString());
          if (o == null) s = "null";
          else s = o.toString();
          if (col < numCols - 1) sb.append(s).append(SEPARATOR);
          else sb.append(s);
        }
        sb.append(NEWLINE);
      }
    } catch (SQLException e) {
      sb.append("ERROR in execution of query: " + e.getMessage());
    } finally {
      Main.getDefaultStorage().close(connection);
    }

    return sb.toString();
  }
예제 #26
0
  public boolean dbOpenList(Connection connection, String sql) {
    dbClearList();
    this.oldSql = sql;
    this.oldConnection = connection;
    // apre il resultset da abbinare
    ResultSet resu = null;
    ResultSetMetaData meta;
    try {
      stat = connection.createStatement();
      resu = stat.executeQuery(sql);
      meta = resu.getMetaData();

      if (meta.getColumnCount() > 1) {
        this.contieneChiavi = true;
      }

      // righe
      while (resu.next()) {
        for (int i = 1; i <= meta.getColumnCount(); ++i) {
          if (i == 1) {
            dbItems.add((Object) resu.getString(i));
            lm.addElement((Object) resu.getString(i));
          } else if (i == 2) {
            dbItemsK.add((Object) resu.getString(i));

            // debug
            // System.out.println("list:" + String.valueOf(i) + ":" + resu.getString(i));
          } else if (i == 3) {
            dbItemsK2.add((Object) resu.getString(i));
          }
        }
      }
      this.setModel(lm);

      // vado al primo
      if (dbTextAbbinato != null) {
        // debug
        // javax.swing.JOptionPane.showMessageDialog(null,this.getKey(0).toString());
        dbTextAbbinato.setText(this.getKey(0).toString());
      }

      return (true);
    } catch (Exception e) {
      javax.swing.JOptionPane.showMessageDialog(null, e.toString());
      e.printStackTrace();
      return (false);
    } finally {
      try {
        stat.close();
      } catch (Exception e) {
      }
      try {
        resu.close();
      } catch (Exception e) {
      }
      meta = null;
    }
  }
예제 #27
0
 /**
  * INTERNAL: Execute the query building the objects directly from the database result-set.
  *
  * @exception DatabaseException - an error has occurred on the database
  * @return object - the first object found or null if none.
  */
 protected Object executeObjectLevelReadQueryFromResultSet() throws DatabaseException {
   UnitOfWorkImpl unitOfWork = (UnitOfWorkImpl) getSession();
   DatabaseAccessor accessor = (DatabaseAccessor) unitOfWork.getAccessor();
   DatabasePlatform platform = accessor.getPlatform();
   DatabaseCall call = (DatabaseCall) getCall().clone();
   call.setQuery(this);
   call.translate(this.translationRow, null, unitOfWork);
   Statement statement = null;
   ResultSet resultSet = null;
   boolean exceptionOccured = false;
   try {
     accessor.incrementCallCount(unitOfWork);
     statement = call.prepareStatement(accessor, this.translationRow, unitOfWork);
     resultSet = accessor.executeSelect(call, statement, unitOfWork);
     ResultSetMetaData metaData = resultSet.getMetaData();
     Vector results = new Vector();
     ObjectBuilder builder = this.descriptor.getObjectBuilder();
     while (resultSet.next()) {
       results.add(
           builder.buildWorkingCopyCloneFromResultSet(
               this,
               this.joinedAttributeManager,
               resultSet,
               unitOfWork,
               accessor,
               metaData,
               platform));
     }
     return results;
   } catch (SQLException exception) {
     exceptionOccured = true;
     DatabaseException commException =
         accessor.processExceptionForCommError(session, exception, call);
     if (commException != null) throw commException;
     throw DatabaseException.sqlException(exception, call, accessor, unitOfWork, false);
   } finally {
     try {
       if (resultSet != null) {
         resultSet.close();
       }
       if (statement != null) {
         accessor.releaseStatement(statement, call.getSQLString(), call, unitOfWork);
       }
     } catch (SQLException exception) {
       if (!exceptionOccured) {
         // in the case of an external connection pool the connection may be null after the
         // statement release
         // if it is null we will be unable to check the connection for a comm error and
         // therefore must return as if it was not a comm error.
         DatabaseException commException =
             accessor.processExceptionForCommError(session, exception, call);
         if (commException != null) throw commException;
         throw DatabaseException.sqlException(exception, call, accessor, session, false);
       }
     }
   }
 }
예제 #28
0
 public List<Type> guessTypes() throws SQLException {
   final ResultSetMetaData metaData = resultSet.getMetaData();
   final int columnCount = metaData.getColumnCount();
   assert this.types == null || this.types.size() == columnCount;
   List<Type> types = new ArrayList<Type>();
   for (int i = 0; i < columnCount; i++) {
     final Type suggestedType = this.types == null ? null : this.types.get(i);
     types.add(guessType(suggestedType, metaData, i));
   }
   return types;
 }
예제 #29
0
파일: Requete.java 프로젝트: tagry/SGBD
 public void print(ResultSet rset) {
   try {
     int nbC = rset.getMetaData().getColumnCount();
     for (int i = 1; i <= nbC; i++) {
       if (i > 1) System.out.print(", ");
       System.out.print(rset.getMetaData().getColumnName(i) + " ");
     }
     System.out.println(" ");
     while (rset.next()) {
       for (int i = 1; i <= nbC; i++) {
         if (i > 1) System.out.print(", ");
         System.out.print(" " + rset.getString(i));
       }
       System.out.println(" ");
     }
     System.out.println(" ");
   } catch (Exception e) {
     System.out.println(e.toString());
   }
 }
  public String[] getColumnNames(ResultSet rs) throws SQLException {
    List<String> names = new ArrayList<String>();
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
      names.add(metadata.getColumnName(i + 1));
    }

    String[] nameArray = new String[names.size()];
    return names.toArray(nameArray);
  }