Ir ao conteúdo
  • Cadastre-se

v1c2rr

Membro Pleno
  • Posts

    44
  • Cadastrado em

  • Última visita

Tudo que v1c2rr postou

  1. Leandronik, valeu pela dica!! Então, eu coloquei as aspas simples naquele script do insert e fiz outra correção para ver se funcionava acrescentando um mais entre "insert into" e "values": String sql = "INSERT INTO pessoa (nome)" + " VALUES('?')"; . O debug quando executei ele deu aquela mesma saída no console e não inseriu aqueles dados que coloquei no fim da classe DAO. Rio: commit nunca usei, como ele ficaria nessa função insert()?!
  2. No console ele não dá erro. Ele só retorna essa saída: run: com.mysql.jdbc.JDBC4Connection@41cf53f9 CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo) e no banco nenhum dado é inserido. Dai agora estou em dúvida se tem algo de errado no banco ou no meu código.
  3. Boa noite pessoal, estou com uma dúvida aqui, Criei 3 classes sendo uma vou, uma dao e a classe de conexão no banco + o banco com 2 campos (id e nome da pessoa) porém ao executar o método principal e verificar a tabela não consegui inserir os dados. Tenho um projeto para entregar até amanhã na faculdade, esse é só um código que estou testando para depois efetuar as mudanças de acordo com esse projeto e implementar o RMI nele. package br.edu.naifcode.dao; import br.edu.naifcode.dto.PessoaDTO; import br.edu.naifcode.jdbc.Conection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; /** * * @author Victor */ public class PessoaDAO { public void inserir(PessoaDTO pessoaDTO) { try { Connection connection = Conection.getInstance().getConnection(); String sql = "INSERT INTO pessoa (nome) VALUES(?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, pessoaDTO.getNome()); statement.execute(); connection.close(); System.out.println("Usuario inserido com sucesso!!"); } catch (Exception e){ e.printStackTrace(); } } public void excluir (int id_pessoa){ try { Connection connection = Conection.getInstance().getConnection(); String sql = "DELETE FROM pessoa WHERE id_pessoa = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, id_pessoa); statement.execute(); statement.close(); } catch (Exception e){ e.printStackTrace(); } } public void atualizar(PessoaDTO pessoaDTO){ try{ Connection connection = Conection.getInstance().getConnection(); String sql = "UPDATE pessoa SET nome = ? WHERE id_pessoa = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, pessoaDTO.getNome()); statement.setInt(2, pessoaDTO.getId_pessoa()); statement.execute(); statement.close(); } catch(Exception e){ e.printStackTrace(); } } public List<PessoaDTO> listarTodos(){ List<PessoaDTO> listaPessoas = new ArrayList<PessoaDTO>(); try{ Connection connection = Conection.getInstance().getConnection(); String sql = "SELECT * FROM pessoa"; //realiza a ponte e executa o script acima no bd PreparedStatement statement = connection.prepareStatement(sql); //vem com a tabela do bd e armazena os dados da tabela do banco no resultset ResultSet resultset = statement.executeQuery(); //enquanto houver linha, serão colocados dados na lista while(resultset.next()){ PessoaDTO pessoaDTO = new PessoaDTO(); pessoaDTO.setId_pessoa(resultset.getInt("id_pessoa")); pessoaDTO.setNome(resultset.getString("nome")); listaPessoas.add(pessoaDTO); } connection.close(); } catch (Exception e){ e.printStackTrace(); } return listaPessoas; } public static void main ( String[] args ) { PessoaDTO pessoaDTO = new PessoaDTO(); pessoaDTO.setNome("Alvaro"); PessoaDAO pessoaDAO = new PessoaDAO(); pessoaDAO.inserir(pessoaDTO); } } package br.edu.naifcode.dto; /** * * @author Victor */ public class PessoaDTO { private int id_pessoa; private String nome; public PessoaDTO() { } public PessoaDTO(int id_pessoa, String nome) { this.id_pessoa = id_pessoa; this.nome = nome; } /** * @return the id_pessoa */ public int getId_pessoa() { return id_pessoa; } /** * @param id_pessoa the id_pessoa to set */ public void setId_pessoa(int id_pessoa) { this.id_pessoa = id_pessoa; } /** * @return the nome */ public String getNome() { return nome; } /** * @param nome the nome to set */ public void setNome(String nome) { this.nome = nome; } } package br.edu.naifcode.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Victor */ public class Conection { private static Conection conection; public static Conection getInstance() { if (conection == null) { conection = new Conection(); } return conection; } public Connection getConnection() throws ClassNotFoundException, SQLException{ Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root",""); } public static void main ( String [] args ){ try { System.out.println(getInstance().getConnection()); } catch (Exception e) { e.printStackTrace(); } } } Banco :test CREATE TABLE IF NOT EXISTS `pessoa` ( `id_pessoa` int(2) NOT NULL, `nome` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `pessoa` -- ALTER TABLE `pessoa` ADD PRIMARY KEY (`id_pessoa`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `pessoa` -- ALTER TABLE `pessoa` MODIFY `id_pessoa` int(2) NOT NULL AUTO_INCREMENT; Espero que alguém me ajude, só preciso de uma dica sobre o está errado no código que não está inserindo dados no banco. Valeu!
  4. Boa tarde senhores Estou realizando um projeto da faculdade que tenho que entregar só até hoje por email, é um projeto de uma pizzaria virtual com html e php. Nele apenas consegui cadastrar os clientes, excluir clientes, e cadastrar as pizzas no banco de dados, porém tenho três dúvidas que faltam no projeto: Como eu faço para realizar a consulta de CEP do site dos correios e ele "jogar" o endereço, bairro, cidade e a uf desse cep nos respectivos campos do formulário que estou trabalhando, e como faço para realizar a consulta dos clientes cadastrados, e para listar as pizzas que foram cadastradas para o usuário escolher a quantidade de cada pizza? Se alguém souber ficarei muito feliz pois é urgente! Obrigado Fiz assim o consultar cep, porém quando clico no botão de submeter ele não pega nenhum dado: <?php if (isset($_GET['cep'])){ $cep = filter_input(INPUT_GET, 'cep'); if(empty($cep)){ echo 'Informe o CEP '; } else { $postCorreios = 'CEP='.$cep.'&Metodo=listarEndereco&TipoConsulta=cep'; $cURL = curl_init("http://www.buscacep.correios.com.br/servicos/dnec/consultaEnderecoAction.do"); curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true); curl_setopt($cURL, CURLOPT_HEADER, false); curl_setopt($cURL, CURLOPT_POST, true); curl_setopt($cURL, CURLOPT_POSTFIELDS, $postCorreios); $saida = curl_exec($cURL); curl_close($cURL); $saida = utf8_encode($saida); $tabela = preg_match_all('@<td (.*?)<\/td>@i', $saida, $campoTabela); echo '<pre>'; print_r($campoTabela); echo '</pre>'; } } ?>
  5. Procurando a respectiva documentação do java.rmi.server.UnicastRemoteObject isso é tudo que eu achei: https://docs.oracle.com/javase/8/docs/api/java/rmi/server/UnicastRemoteObject.html Aqui ele fala que a quarta opção é obsoleta por gerar stubs estáticos e skeletons (que eles falam serem desconsiderados) e o erro diz que usuários são encorajados a deixarem de utilizar o comando rmic para gerar stubs estáticos e skeletons, e que eu devo realizar os cinco outros passos: Subclassing UnicastRemoteObject and calling the UnicastRemoteObject() constructor. Subclassing UnicastRemoteObject and calling the UnicastRemoteObject(port) constructor. Subclassing UnicastRemoteObject and calling the UnicastRemoteObject(port, csf, ssf) constructor. Calling the exportObject(Remote, port) method. Calling the exportObject(Remote, port, csf, ssf) method. E aqui está o código: import java.rmi.RemoteException;import java.rmi.server.UnicastRemoteObject;import static java.rmi.server.UnicastRemoteObject.exportObject;import java.sql.*; public class Implementacao extends UnicastRemoteObject implements Interfacebd { public Implementacao() throws RemoteException{ super(); } public Connection conexao() throws RemoteException{ //String servidor = "jdbc:mysql://127.0.0.1:3306/"; String servidor = "jdbc:mysql://localhost/agenda"; String nomebanco = "usuario"; String usuario = "root"; String senha = ""; String driver = "com.mysql.jdbc.Driver"; String url = servidor + nomebanco + "&user=" + usuario + "&password=" + senha; try{ Class.forName(driver).newInstance(); Connection con = DriverManager.getConnection(url, usuario, senha); return con; }catch(SQLException ex){ System.out.println(ex.getMessage()); return null; }catch(Exception e){ System.out.println(e.getMessage()); return null; } } @[member="override"] public String consultanome(int sid) throws RemoteException { String s = null; try{ Connection myconn = conexao(); Statement comando = myconn.createStatement(); ResultSet rs = comando.executeQuery("SELECT * FROM usuario WHERE id= " + sid); while (rs.next()){ s = (rs.getString(2)); } rs.close(); comando.close(); myconn.close(); return s; } catch(SQLException ex){ System.out.println(ex.getMessage()); return null; } catch(Exception e){ System.out.println(e.getMessage()); return null; } } @[member="override"] public String consultaemail(int sid) throws RemoteException { String s = null; try{ Connection myconn = conexao(); Statement comando = myconn.createStatement(); ResultSet rs = comando.executeQuery("SELECT * FROM usuario WHERE id= " + sid); while (rs.next()){ s = (rs.getString(3)); } rs.close(); comando.close(); myconn.close(); return s; } catch(SQLException ex){ System.out.println(ex.getMessage()); return null; } catch(Exception e){ System.out.println(e.getMessage()); return null; } } @[member="override"] public String consultasenha(int sid) throws RemoteException { String s = null; try{ Connection myconn = conexao(); Statement comando = myconn.createStatement(); ResultSet rs = comando.executeQuery("SELECT * FROM usuario WHERE id= " + sid); while (rs.next()){ s = (rs.getString(4)); } rs.close(); comando.close(); myconn.close(); return s; } catch(SQLException ex){ System.out.println(ex.getMessage()); return null; } catch(Exception e){ System.out.println(e.getMessage()); return null; } }} Dai nesse caso o que preciso mudar no código e como gerar ele sem utilizar o rmic?!
  6. Boa Noite! Criei um projeto no NetBeans 8.0.2 em Java com JDK 8u45 utilizando arquitetura RMI Cliente Servidor com acesso a banco de dados, porém, quando vou tentar criar os arquivos stubs e skeletons na classe de Implementação a partir do cmd com o rmic a seguinte mensagem aparece: "Warning: generation and use of skeletons and static stubs for JRMP is deprecated. Skeletons are unnecessary, and static stubs have been superseded by dynamically generated stubs. Users are encouraged to migrate away from using rmic to generate skeletons and static stubs. See the documentation for java.rmi.server.UnicastRemoteObject." Gostaria de saber se é possível realizar essa geração de objetos remotos em outro lugar ou o que tenho que fazer para resolver esse problema?! Já tentei procurar em toda a net a resposta do problema já tentei instalar outra versão do JDK pois não sei se essa porém não funcionou, quem puder me ajudar estarei muito grato!! Obrigado desde já
  7. Fala ai Pessoal!! beleza?! Estou querendo implementar um código que faça as funcionalidades do CRUD (Inserir, Alterar, Excluir e Pesquisar) de preferência via Cliente Servidor em plataforma RMI no Netbeans, o problema é que não sei por onde eu tenho que começar e a ideia dessa arquitetura ficou pouco clara. A ideia é realizar o cadastro de itens e a manipulação deles aonde o Banco fique do lado do Server. Se alguém puder ajudar eu agradeço muito! Não achei nada na net pronto explicando e é para um projeto daqui duas semanas. Valeu!!
  8. Na saída ele deu esse erro quando cliquei no Cadastro de Associado: debug:Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException: Not supported yet.at PersistenciaDAO.LoginDAO.<init>(LoginDAO.java:33)at View.FormLogin.<init>(FormLogin.java:37)at View.FormMuseu.jmLoginActionPerformed(FormMuseu.java:301)at View.FormMuseu.access$100(FormMuseu.java:18)at View.FormMuseu$2.actionPerformed(FormMuseu.java:112)at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)at javax.swing.AbstractButton.doClick(AbstractButton.java:376)at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:289)at java.awt.Component.processMouseEvent(Component.java:6525)at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)at java.awt.Component.processEvent(Component.java:6290)at java.awt.Container.processEvent(Container.java:2234)at java.awt.Component.dispatchEventImpl(Component.java:4881)at java.awt.Container.dispatchEventImpl(Container.java:2292)at java.awt.Component.dispatchEvent(Component.java:4703)at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)at java.awt.Container.dispatchEventImpl(Container.java:2278)at java.awt.Window.dispatchEventImpl(Window.java:2750)at java.awt.Component.dispatchEvent(Component.java:4703)at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:751)at java.awt.EventQueue.access$500(EventQueue.java:97)at java.awt.EventQueue$3.run(EventQueue.java:702)at java.awt.EventQueue$3.run(EventQueue.java:696)at java.security.AccessController.doPrivileged(Native Method)at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)at java.awt.EventQueue$4.run(EventQueue.java:724)at java.awt.EventQueue$4.run(EventQueue.java:722)at java.security.AccessController.doPrivileged(Native Method)at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)at java.awt.EventQueue.dispatchEvent(EventQueue.java:721)at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) Nesse caso como devo proceder? Estou perdido aqui
  9. Boa noite senhores Estou fazendo um sistema de Museu em Java pelo Netbeans que é o trabalho da minha faculdade, tudo por enquanto está bem quando executo o menu principal e clico em cada aba ele chama as opções e tal, porém estou tendo problema na inserção dos campos da textField na tabela tabassociado nos códigos a seguir. Não sei se esse é o jeito certo de mostrar minha dúvida ou se seria melhor mandar o projeto inteiro, mas vamos lá: Classe de conexão com o banco: package Banco;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;public class Banco { private String usuario, senha, servidor, nomebanco; private int porta; private Connection conexao = null; public Banco(){ } public Banco(String usuario, String senha, String servidor, String nomebanco, int porta){ this.usuario = usuario; this.senha = senha; this.servidor = servidor; this.nomebanco = nomebanco; this.porta = porta; } public String getUsuario(){ return usuario; } /* Getters e setters... */ /* * Recebe a conexão e retorna a mesma do banco de dados */ public Connection getConexao(){ return conexao; } /** * Abre o Banco de Dados, realiza tentativa de pegar a conexao atraves do Driver JDBC, caso contrario a conexao * retorna NULL */ public void abrir() { try { Class.forName("com.mysql.jdbc.Driver"); conexao = DriverManager.getConnection("jdbc:mysql://" + getServidor() + ":" + getPorta() + "/" + getNomebanco(), getUsuario(), getSenha()); } catch (SQLException ex) { ex.printStackTrace(); conexao = null; } catch (ClassNotFoundException ex) { ex.printStackTrace(); conexao = null; } } /** * Fecha a conexao com o banco de dados */ public void fechar() { try { conexao.close(); } catch (SQLException ex) { ex.printStackTrace(); } } /** *Atualiza a conexao com o Banco de dados * */ public int atualizar(String sql) { /**Chama um objeto stm de Statement que chama os metodos getConexao junto com createStatement e retorna * atualiza caso der certo, se nao, imprime a pilha de erros de exception */ try { Statement stm = getConexao().createStatement(); return stm.executeUpdate(sql); } catch (SQLException ex) { ex.printStackTrace(); return -1; } } } Controller Associado: package Controller;import Model.Associado;import PersistenciaDAO.AssociadoDAO;import java.sql.SQLException;import java.util.ArrayList;import java.util.logging.Level;import java.util.logging.Logger;public class ControleAssociado { private Associado objAssociado; public boolean SalvarAssociado(Object obj){ try { return new AssociadoDAO().inserir(obj); } catch (SQLException ex) { ex.printStackTrace(); return false; } }} vou Associado (Model): package Model;/** * * @author Victor */public class Associado { private String nome, rua, complemento, cidade, bairro, estado, dataNascimento; private int idAssociado, numero, cep, rg, cpf, telCom, telRes, telCel; private Login login; public Associado(){} public Associado(int idAssociado, String nome, String dataNascimento, String rua, String complemento, int numero, String cidade, String bairro, int cep, String estado, int rg, int cpf, int telCom, int telRes, int telCel){ this.idAssociado = idAssociado; this.nome = nome; this.dataNascimento = dataNascimento; this.rua = rua; this.complemento = complemento; this.numero = numero; this.cidade = cidade; this.bairro = bairro; this.cep = cep; this.estado = estado; this.rg = rg; this.cpf = cpf; this.telCom = telCom; this.telRes = telRes; this.telCel = telCel; } /** * @[member=Return] the nome */ public String getNome() { return nome; } /* Getters e setters... */} DAO de Associado (persistência): package PersistenciaDAO;import Model.Associado;import Banco.Banco;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.List;import java.util.Vector;/** * * @author Victor */public class AssociadoDAO implements DAO { PreparedStatement pstm = null; Statement stm = null; Banco banco = new Banco("root","","localhost","museu",3306); ResultSet rs = null; String sql = null; public AssociadoDAO(){ this.banco=banco; } @[member=override] public boolean inserir(Object obj) throws SQLException { Associado associado; if(obj instanceof Associado){ associado=(Associado)obj; }else{ return false; } sql="INSERT INTO tabassociado (nome, dataNascimento, rua, complemento, numero, cidade, bairro, cep, estado, rg, cpf, telCom, telRes, telCel)" + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; banco.abrir(); pstm = banco.getConexao().prepareStatement(sql); pstm.setString(1, associado.getNome()); pstm.setString(2, associado.getDataNascimento()); pstm.setString(3, associado.getRua()); pstm.setString(4, associado.getComplemento()); pstm.setInt (5, associado.getNumero()); pstm.setString(6, associado.getCidade()); pstm.setString(7, associado.getBairro()); pstm.setInt (8, associado.getCep()); pstm.setString(9, associado.getEstado()); pstm.setInt (10, associado.getRg()); pstm.setInt (11, associado.getCpf()); pstm.setInt (12, associado.getTelCom()); pstm.setInt (13, associado.getTelRes()); pstm.setInt (14, associado.getTelCel()); boolean retorno; retorno = (pstm.executeUpdate() == 0 ? false : true ); banco.fechar(); return retorno; } @[member=override] public boolean alterar(Object obj) throws SQLException { Associado associado; if(obj instanceof Associado){ associado=(Associado)obj; }else{ return false; } sql = "UPDATE tabassociado SET nome = '" +associado.getNome()+ "', dataNascimento ='" +associado.getDataNascimento()+ "',rua ='" +associado.getRua()+ "', " + "complemento = '" +associado.getComplemento()+ "' , numero = '" +associado.getNumero()+ "', cidade ='" +associado.getCidade()+ "', " + "bairro ='" +associado.getBairro()+ "', cep = '" +associado.getCep()+ "', estado = '" +associado.getEstado()+ "', rg = '" +associado.getRg()+ "', " + "cpf = '" +associado.getCpf()+ "', telCom = '" +associado.getTelCom()+ "', telRes = '" +associado.getTelRes()+ "', telCel = '" +associado.getTelCel()+ "', " + "WHERE idAssociado ='" +associado.getIdAssociado()+ "'"; banco.abrir(); stm = banco.getConexao().prepareStatement(sql); if(stm.executeUpdate(sql)>0){ banco.fechar(); return true; } else { return false; } } @[member=override] public boolean excluir(Object obj) throws SQLException { Associado associado; if(obj instanceof Associado){ associado =(Associado)obj; }else{ return false; } sql = "DELETE FROM tabassociado WHERE nome ='"+associado.getNome()+"'"; banco.abrir(); stm = banco.getConexao().prepareStatement(sql); if(stm.executeUpdate(sql)>0){ banco.fechar(); return true; } else { return false; } } @[member=override] public Object pesquisar(int pk) throws SQLException { Associado ass = null; sql= "SELECT * FROM tabassociado WHERE idAssociado =" + pk; banco.abrir(); stm = banco.getConexao().createStatement(); rs = stm.executeQuery(sql); if(rs.next()){ ass = new Associado(); ass.setNome(rs.getString("nome")); } rs.close(); banco.fechar(); return ass; } @[member=override] public List listar(String criterio) throws SQLException { Associado ass = null; Vector lista = new Vector <Associado>(); if(criterio.isEmpty()){ sql= "SELECT * FROM tabassociado"; } else { sql= "SELECT * FROM tabassociado WHERE = " + criterio; banco.abrir(); stm = banco.getConexao().createStatement(); rs = stm.executeQuery(sql); while(rs.next()){ //Recebe o conteúdo da tabela e insere diretamente na lista ass = new Associado(); ass.setNome(rs.getString("nome")); ass.setDataNascimento(rs.getString("dataNascimento")); ass.setRua(rs.getString("rua")); ass.setComplemento(rs.getString("complemento")); ass.setNumero(rs.getInt("numero")); ass.setCidade(rs.getString("cidade")); ass.setBairro(rs.getString("bairro")); ass.setCep(rs.getInt("cep")); ass.setEstado(rs.getString("estado")); ass.setRg(rs.getInt("rg")); ass.setCpf(rs.getInt("cpf")); ass.setTelCom(rs.getInt("telCom")); ass.setTelRes(rs.getInt("telRes")); ass.setTelCel(rs.getInt("telCel")); lista.add(ass); //fecha o Banco e o Resultset } banco.fechar(); return lista; } return null; } public boolean login(String login, String senha) throws SQLException { Associado ass = null; sql= "SELECT * FROM associado WHERE login='"+login+"' and senha= '"+senha+"'"; //sql="select * from teste"; banco.abrir(); stm = banco.getConexao().createStatement(); rs = stm.executeQuery(sql); if(rs.next()){ if((rs.getString("login").equalsIgnoreCase(login)) && (rs.getString("senha").equalsIgnoreCase(senha))){ rs.close(); banco.fechar(); return true; } else { rs.close(); banco.fechar(); return false; } } else return false; } } View de Associado: package View;import Controller.ControleAssociado;import Model.Associado;import javax.swing.JOptionPane;public class FormCadAssociado extends javax.swing.JFrame { /** * Creates new form FormAssociado */ public FormCadAssociado() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") /* Generated Code */ private void jbtCadastrarActionPerformed(java.awt.event.ActionEvent evt) { Associado associado = new Associado(); associado.setNome(jtfNome.getText()); associado.setDataNascimento(jtfDataNasc.getText()); associado.setRua(jtfRua.getText()); associado.setComplemento(jtfComplemento.getText()); associado.setNumero(Integer.parseInt(jtfNumero.getText())); associado.setCidade(jtfCidade.getText()); associado.setBairro(jtfBairro.getText()); associado.setCep(Integer.parseInt(jtfCep.getText())); associado.setEstado(jtfEstado.getText()); associado.setRg(Integer.parseInt(jtfRg.getText())); associado.setCpf(Integer.parseInt(jtfCpf.getText())); associado.setTelCom(Integer.parseInt(jtfTelCom.getText())); associado.setTelRes(Integer.parseInt(jtfTelRes.getText())); associado.setTelCel(Integer.parseInt(jtfTelCel.getText())); ControleAssociado ctass = new ControleAssociado(); ctass.SalvarAssociado(associado); JOptionPane.showMessageDialog(this, "Associado cadastrado com sucesso!"); limparTextField(); } public void limparTextField(){ jtfNome.setText(""); jtfDataNasc.setText(""); jtfRua.setText(""); jtfComplemento.setText(""); jtfNumero.setText(""); jtfCidade.setText(""); jtfBairro.setText(""); jtfCep.setText(""); jtfEstado.setText(""); jtfRg.setText(""); jtfCpf.setText(""); jtfTelCel.setText(""); jtfTelCom.setText(""); jtfTelRes.setText(""); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FormCadAssociado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormCadAssociado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormCadAssociado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormCadAssociado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FormCadAssociado().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JButton jbtCadastrar; private javax.swing.JButton jbtNovo; private javax.swing.JButton jbtVoltar; private javax.swing.JTextField jtfBairro; private javax.swing.JTextField jtfCep; private javax.swing.JTextField jtfCidade; private javax.swing.JTextField jtfComplemento; private javax.swing.JTextField jtfCpf; private javax.swing.JTextField jtfDataNasc; private javax.swing.JTextField jtfEstado; private javax.swing.JTextField jtfNome; private javax.swing.JTextField jtfNumero; private javax.swing.JTextField jtfRg; private javax.swing.JTextField jtfRua; private javax.swing.JTextField jtfTelCel; private javax.swing.JTextField jtfTelCom; private javax.swing.JTextField jtfTelRes; // End of variables declaration } Dai quando preencho cada campo e dou validar ele dá erros na hora da saída como por exemplo: java.awt.event....(letras vermelhas). Gostaria de saber o que está errado em alguma das classes e o que precisaria ser alterado afim de funcionar o código? Ficaria muito grato pela ajuda!! Se alguém precisar do projeto completo para visualizar melhor também tenho o código fonte para disponibilizar. Grato, Victor
  10. Boa Noite, estou fazendo o seguinte exercício que consta em: Ler 20 registros a partir da Sysin(Regvenda) Os registros já devem estar classificados por código Mostrar o valor total de vendas, consolidados por filial (quebra simples) No final exibir total e parar processamento Assim a Sysout seria por exemplo: Relatorio Consolidado Por FilialFilial Total Vendas99 Z.ZZZ.ZZ9,99... ............. ..........TOTAL GERAL: ZZ.ZZZ.ZZ9,99 Meu programa (Coblib) ficou assim: IDENTIFICATION DIVISION. *=======================* PROGRAM-ID. FTCOB008. *AUTHOR. VICTOR BORGHI GIMENEZ. *DATE-WRITTEN. 06/04/2015. *--------------------------------------------------------------** OBJETIVO: RECEBER DADOS DA SYSIN(ACCEPT) * CALCULAR AS VENDAS REALIZADAS POR CADA FILIAL *--------------------------------------------------------------**------------------> HISTORICO - MANUTENCAO <------------------** VERSAO MES/ANO NR.DOC IDENT. DESCRICAO * ------ ------- ------ ------ ------------------------- ** V01 ABR/2015 010001 SISTEMA MOSTRA SYSOUT *--------------------------------------------------------------* ENVIRONMENT DIVISION. *====================* CONFIGURATION SECTION. *---------------------* SPECIAL-NAMES. DECIMAL-POINT IS COMMA CURRENCY SIGN IS "R$ " WITH PICTURE SYMBOL "$" . INPUT-OUTPUT SECTION. *---------------------* DATA DIVISION. *=============* FILE SECTION. *------------* WORKING-STORAGE SECTION. *-----------------------* 01 FILLER PIC X(35) VALUE '**** INICIO DA WORKING-STORAGE ****'. *-----> VARIAVEIS AUXILIARES UTILIZADA NO PROCESSAMENTO 01 WS-AREA-AUX. 05 WS-FIM PIC X(01). 05 WS-CTLIDO PIC 9(02). 05 WS-VENDA-ANT PIC 9(6)V99. 05 WS-FILIAL-ANT PIC 9(2)V99. 05 WS-TOTALVENDAS PIC 9(7)V99. *-----> ENTRADA - DADOS VIA SYSIN (NO JCL DE EXECUCAO) 01 WS-REGVENDA. 05 WS-CODIGO. 07 WS-FILIAL PIC 9(2). 07 WS-DEPTO PIC 9(2). 07 WS-NUM PIC 9(3). 05 WS-NOME PIC X(20). 05 WS-VENDA PIC 9(6)V99. 01 FILLER PIC X(35) VALUE SPACES. *-----> SAIDA - DADOS VIA SYSOUT 01 CAB1. 03 FILLER PIC X(50) VALUE "RELATORIO CONSOLIDADO POR FILIAL". 01 CAB2. 03 FILLER PIC X(50) VALUE "FILIAL TOTAL VENDAS". 01 DEP. 03 FILLER PIC X(02). 03 FILIAL-DEP PIC X(02). 03 FILLER PIC X(02). 03 TOTALVENDAS-DEP PIC Z.ZZZ.ZZ9,99. 01 FILLER PIC X(35) VALUE '****** FIM DA WORKING-STORAGE *****'. * PROCEDURE DIVISION. *==================* *--------------------------------------------------------------* * PROCESSO PRINCIPAL *--------------------------------------------------------------* 000-FTCOB008. PERFORM 010-INICIAR PERFORM 030-PROCESSAR UNTIL WS-FIM = 'S' PERFORM 090-TERMINAR STOP RUN . *--------------------------------------------------------------* * PROCEDIMENTOS INICIAIS *--------------------------------------------------------------* 010-INICIAR. DISPLAY CAB1 DISPLAY CAB2 PERFORM 025-LER-SYSIN . *--------------------------------------------------------------** LEITURA DADOS DA SYSIN *--------------------------------------------------------------* 025-LER-SYSIN. ACCEPT WS-REGVENDA FROM SYSIN IF WS-REGVENDA = ALL '9' MOVE 'S' TO WS-FIM ELSE ADD 1 TO WS-CTLIDO END-IF . *--------------------------------------------------------------** PROCESSAR DADOS RECEBIDOS DA SYSIN ATE FIM DOS REGISTROS *--------------------------------------------------------------* 030-PROCESSAR. PERFORM 032-SOMAR-REGISTROS PERFORM 025-LER-SYSIN . *--------------------------------------------------------------* * SOMAR REGISTROS POR CODIGO *--------------------------------------------------------------* 032-SOMAR-REGISTROS. PERFORM WS-REGVENDA FROM 1 TO 20 WHILE MOVE WS-FILIAL TO WS-FILIAL-ANT MOVE WS-VENDA TO WS-VENDA-ANT IF WS-FILIAL-ANT = WS-FILIAL COMPUTE WS-TOTAL = WS-VENDA + WS-VENDA-ANT ELSE MOVE WS-FILIAL TO FILIAL-DEP MOVE WS-TOTALVENDAS TO TOTALVENDAS-DEP DISPLAY DEP END IF . *----------------------------------------------------------------** PROCEDIMENTOS FINAIS *----------------------------------------------------------------* 090-TERMINAR. DISPLAY ' *========================================*' DISPLAY ' * TOTAIS DE CONTROLE - FTCOB008*' DISPLAY ' *----------------------------------------*' DISPLAY ' * REGISTROS LIDOS - SYSIN = ' WS-CTLIDO DISPLAY ' *========================================*' DISPLAY ' *----------------------------------------*' DISPLAY ' * TERMINO NORMAL DO FTCOB008*' DISPLAY ' *----------------------------------------*' . *---------------> FIM DO PROGRAMA FTCOB008 <-------------------* E a massa de dados (Joblib): -Warning- The UNDO command is not available until you change your edit profile using the command RECOVERY ON. //GPAZ99J2 JOB ,MSGCLASS=X,CLASS=C,NOTIFY=GPAZ99,TIME=(0,20)//*****************************************************************//* LER DADOS DA SYSIN - REGISTRO COM '99...99' INDICA FIM DOS REG.//*****************************************************************//STEP1 EXEC PGM=FTCOB008 //STEPLIB DD DSN=GP.GERAL.LOADLIB,DISP=SHR //SYSIN DD * 0109111MARIA DAS GRACAS 00014050 0101121FERNANDO RODRIGUES 01550000 0101121SUELI MATHIAS 00024050 0204121CASSIO DE SOUZA 01000000 ......................................................................000026 3010121LUCIANO TEIXEIRA 00128700 000027 5009121MICHEL COSTA BASTOS 00300000 000028 99999999999999999999999999999999999999 000029 //* ****** **************************** Bottom of Data **************************** *Total de 20 registros Só que compilando isso na Compcob está indo normalmente dando saída OK (Maxcc=0) mas na massa de dados segui as regras na hora de declarar as variáveis nos tamanhos solicitados mas a saída deu : 06.17.42 JOB01557 $HASP165 GPAZ99J2 ENDED AT N1 - ABENDED S806 U0000 CN(INTERNA L). Nesse caso gostaria de saber se a lógica que usei está correta e como eu poderia percorrer todos os registros somando dados das vendas de mesmas filiais, nesse caso se está certo o perform que estou utilizando ou teria que ser só por if?! Valeu!! alguém??

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...