Example #1
0
 public void actionPerformed(ActionEvent e) {
   if (e.getSource() == b) {
     if (makeConnection()) {
       if (!t1.getText().equals("")
           & !t2.getText().equals("")
           & !t3.getText().equals("")
           & !t4.getText().equals("")) {
         det dez = new det();
         if (dez.date(t4.getText())) {
           String a = t1.getText();
           String b = t2.getText();
           String c = t3.getText();
           String d = t4.getText();
           String ef = t5.getText();
           try {
             st = cn.createStatement();
             String sql = "insert into detalle_ventas values('";
             sql += a;
             sql += "', '";
             sql += b + "', '" + c + "', '" + d + "', '" + ef;
             sql += "')";
             int eaz = st.executeUpdate(sql);
             javax.swing.JOptionPane.showMessageDialog(
                 null,
                 "Se han creado " + eaz + " registros en la base de datos",
                 "informacion",
                 javax.swing.JOptionPane.INFORMATION_MESSAGE);
             start();
           } catch (SQLException exz) {
             javax.swing.JOptionPane.showMessageDialog(
                 null,
                 "Ha ocurrido un error, favor de checar que la clave no ha sido ingresada ya con anterioridad  \n si el problema persiste contacte con el administrador \nError: "
                     + exz.getSQLState()
                     + ""
                     + exz.getMessage(),
                 "Error",
                 javax.swing.JOptionPane.INFORMATION_MESSAGE);
           } catch (Exception ez) {
             System.out.println(ez.getMessage());
           }
         } else {
           javax.swing.JOptionPane.showMessageDialog(
               null,
               "Favor de llenar la fecha con un formato correcto dd/mm/aaaa",
               "Error!!!",
               javax.swing.JOptionPane.ERROR_MESSAGE);
         }
       } else {
         javax.swing.JOptionPane.showMessageDialog(
             null,
             "Favor de llenar todos los datos correctamente",
             "Error!!!",
             javax.swing.JOptionPane.ERROR_MESSAGE);
       }
     } else {
       javax.swing.JOptionPane.showMessageDialog(
           null,
           "Un error ha ocurrido al intentar conectar con la base de datos, \n reinicie el componente o contacte con el administrador",
           "Error",
           javax.swing.JOptionPane.ERROR_MESSAGE);
     }
   }
   try {
     cn.close();
   } catch (Exception esa) {
     System.out.println(esa.getMessage());
   }
 }
  private void execute() {

    gResult.clear();

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    try {
      lTime = System.currentTimeMillis();

      sStatement.execute(sCmd);

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = "" + r;

        gResult.addRow(g);
      }

      lTime = System.currentTimeMillis() - lTime;

      addToRecent(txtCommand.getText());
      gResult.fireTableChanged(null);
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
      gResult.fireTableChanged(null);
    }

    updateResult();
    System.gc();
  }
  public ItensVendidos() {
    super("Itens Vendidos");
    JButton imprimir;

    final DefaultTableModel modelo = new DefaultTableModel();

    // constrói a tabela
    JTable tabela = new JTable(modelo);

    // Cria duas colunas
    modelo.addColumn("Código");
    modelo.addColumn("Vendedor");
    modelo.addColumn("Produto");
    modelo.addColumn("Quantidade");

    imprimir = new JButton("Imprimir");
    imprimir.setBounds(100, 450, 30, 24);

    // exibe os dados da tabela MySQL
    // Conexao banco = new Conexao();
    String retorno = "erro";
    try {
      // Connection ExConn = (Connection) banco.abrirBDconn();
      Class.forName("com.mysql.jdbc.Driver");
      Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost/banco", "root", "");
      Statement stmt = conexao.createStatement();

      // procedimentos para obter os dados de uma tabela

      String query = "SELECT * FROM venda2";
      ResultSet rs = stmt.executeQuery(query);

      while (rs.next()) {
        int id = rs.getInt("idVendedor");
        String nome = rs.getString("nomeVendedor");
        String produto = rs.getString("produto");
        int qtd = rs.getInt("qtd");
        modelo.addRow(new Object[] {new Integer(id), nome, produto, new Integer(qtd)});
      }

      // fim procedimento para obter os dados
    } catch (SQLException ex) {
      System.out.println("SQLException: " + ex.getMessage());
      System.out.println("SQLState: " + ex.getSQLState());
      System.out.println("VendorError: " + ex.getErrorCode());
    } catch (Exception e) {
      System.out.println("Problemas ao tentar conectar com o banco de dados");
    }
    // fim MySQL

    tabela.setPreferredScrollableViewportSize(new Dimension(350, 50));

    Container c = getContentPane();
    c.setLayout(new FlowLayout());

    JScrollPane scrollPane = new JScrollPane(tabela);
    c.add(scrollPane);
    c.add(imprimir);

    setSize(400, 300);
    setVisible(true);
  }
  /* Clear all existing nodes from the tree model and rebuild from scratch.
   */
  protected void refreshTree() {

    DefaultMutableTreeNode propertiesNode;
    DefaultMutableTreeNode leaf;

    // First clear the existing tree by simply enumerating
    // over the root node's children and removing them one by one.
    while (treeModel.getChildCount(rootNode) > 0) {
      DefaultMutableTreeNode child = (DefaultMutableTreeNode) treeModel.getChild(rootNode, 0);

      treeModel.removeNodeFromParent(child);
      child.removeAllChildren();
      child.removeFromParent();
    }

    treeModel.nodeStructureChanged(rootNode);
    treeModel.reload();
    tScrollPane.repaint();

    // Now rebuild the tree below its root
    try {

      // Start by naming the root node from its URL:
      rootNode.setUserObject(dMeta.getURL());

      // get metadata about user tables by building a vector of table names
      String usertables[] = {"TABLE", "GLOBAL TEMPORARY", "VIEW"};
      ResultSet result = dMeta.getTables(null, null, null, usertables);
      Vector tables = new Vector();

      // sqlbob@users Added remarks.
      Vector remarks = new Vector();

      while (result.next()) {
        tables.addElement(result.getString(3));
        remarks.addElement(result.getString(5));
      }

      result.close();

      // For each table, build a tree node with interesting info
      for (int i = 0; i < tables.size(); i++) {
        String name = (String) tables.elementAt(i);
        DefaultMutableTreeNode tableNode = makeNode(name, rootNode);
        ResultSet col = dMeta.getColumns(null, null, name, null);

        // sqlbob@users Added remarks.
        String remark = (String) remarks.elementAt(i);

        if ((remark != null) && !remark.trim().equals("")) {
          makeNode(remark, tableNode);
        }

        // With a child for each column containing pertinent attributes
        while (col.next()) {
          String c = col.getString(4);
          DefaultMutableTreeNode columnNode = makeNode(c, tableNode);
          String type = col.getString(6);

          makeNode("Type: " + type, columnNode);

          boolean nullable = col.getInt(11) != DatabaseMetaData.columnNoNulls;

          makeNode("Nullable: " + nullable, columnNode);
        }

        col.close();

        DefaultMutableTreeNode indexesNode = makeNode("Indices", tableNode);
        ResultSet ind = dMeta.getIndexInfo(null, null, name, false, false);
        String oldiname = null;

        // A child node to contain each index - and its attributes
        while (ind.next()) {
          DefaultMutableTreeNode indexNode = null;
          boolean nonunique = ind.getBoolean(4);
          String iname = ind.getString(6);

          if ((oldiname == null || !oldiname.equals(iname))) {
            indexNode = makeNode(iname, indexesNode);

            makeNode("Unique: " + !nonunique, indexNode);

            oldiname = iname;
          }

          // And the ordered column list for index components
          makeNode(ind.getString(9), indexNode);
        }

        ind.close();
      }

      // Finally - a little additional metadata on this connection
      propertiesNode = makeNode("Properties", rootNode);

      makeNode("User: "******"ReadOnly: " + cConn.isReadOnly(), propertiesNode);
      makeNode("AutoCommit: " + cConn.getAutoCommit(), propertiesNode);
      makeNode("Driver: " + dMeta.getDriverName(), propertiesNode);
      makeNode("Product: " + dMeta.getDatabaseProductName(), propertiesNode);
      makeNode("Version: " + dMeta.getDatabaseProductVersion(), propertiesNode);
    } catch (SQLException se) {
      propertiesNode = makeNode("Error getting metadata:", rootNode);

      makeNode(se.getMessage(), propertiesNode);
      makeNode(se.getSQLState(), propertiesNode);
    }

    treeModel.nodeStructureChanged(rootNode);
    treeModel.reload();
    tScrollPane.repaint();
  }