Ajuda para salvar dados no access

2 respostas
DANIEL35
Olá pessoal, consegui conectar minha aplicação no access, mas agora estou precisando salvar meus dados nas tabelas que criei. Pesquisei bastante, mas ainda estou com dificuldades. Como devo fazer para conseguir salvar na tabela aluno corretamente? Devo inserir os "insert" na classe da conexão ou na classe que tem o tratamento do botão salvar? Vejam o código:
import javax.swing.*;
import java.awt.*;   
import java.awt.event.*;   
import java.sql.*;   
import javax.swing.*;

public class ConexaoAccess {
 Connection conexao; //instância do objeto de conexão
 JTextField c1, c2;  
 public ConexaoAccess() {
     try {
     	Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // O sun.jdbc.odbc.JdbcOdbcDriver significa que será usado um banco access
        String url = "jdbc:odbc: Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/Banco/academia.mdb";// esta string carrega o nome da fonte de dados
        conexao = DriverManager.getConnection(url,"","");// aqui é efetuada conexão passando a fonte de dados e o login e senha do banco, que neste caso não existem.		
        Statement st = conexao.createStatement();   
        st.executeUpdate("INSERT INTO Aluno (Matricula, nome) VALUES ('"+   
                     c1.getText() +"','"+   
                     c2.getText() +"')");  
                      
     }
     catch ( ClassNotFoundException cnfex ) {
     	System.err.println("FALHA AO CARREGAR o JDBC/ODBC driver.");
        System.exit(0);
        }
      catch (SQLException ex) {
      	System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
        }        
 }//construtor
  
 public void shutDown(){  // este método cancela a conexão
         try {
         conexao.close();
         }
         catch ( SQLException sqlex ) {
          System.err.println( "Não foi possível desconectar" );
         }       
  }
 public Connection getConn(){  // este método retorna a conexão
  return conexao;
 } 
}

2 Respostas

D

eu faria da seguinte forma:
essa clase que vc ta usando “ConexaoAccess”, apenas serviria para a parte de conexão com o banco.
e criaria outra classe “Aluno”, que usaria para fazer os metodos, cadastrar aluno, por exemplo, ai sim nesse metodo validaria os dados e usaria a outra classe para a insersão.
ficou claro??? ou seja, uma classe só para banco, e outra para interface…
vlw

DANIEL35
Então na verdade eu estou tentando fazer isso. Eu criei essa classe ConexaoAccess, que está conectando direitinho, e na classe CadastroAluno, vou colocar o resto. Minha dúvida mesmo, é na maneira de salvar os dados no banco, pois está dando erros. Veja o código:
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;     
import javax.swing.text.MaskFormatter;  
import javax.swing.JOptionPane;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.text.ParseException;
import java.text.SimpleDateFormat;  
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.Calendar;
import java.sql.*;  

public class CadastroAluno extends JFrame{
    private JButton b1, b2, b3, b4;
    private JLabel l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14, l15, l16;
    private JTextField c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c14, c15, c16, c17, c18;
    private TratarBotoesTelaAluno tba;
    private JComboBox combo, combo_2, combo_3, combo_4; 
    private JFormattedTextField dat, telefone, telefone_cel, cpf, cep; 
    private MaskFormatter Dat, Tel, Tel_cel, CPF, CEP;
		
	public CadastroAluno() {
		setTitle("CADASTRO DE ALUNOS");			
	    JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout(FlowLayout.LEFT));       
		JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3,0,3,5));  
        JPanel p3 = new JPanel(); p3.setLayout(new FlowLayout(3));         
        
        Icon bug = new ImageIcon("travelbug.gif");   
    	JLabel l0 = new JLabel(new ImageIcon("C:\PPI\CADASTRO.jpg"));
    	p1.add(l0); 
    	
    	try {  
            Tel = new MaskFormatter("##-####-####");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } 
        try {  
            Tel_cel = new MaskFormatter("##-####-####");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }         
        try {  
            Dat = new MaskFormatter("##/##/####");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        try {  
           CPF = new MaskFormatter("###-###-###-##");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }
        try {  
           CEP = new MaskFormatter("#####-###");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }                    
        telefone = new JFormattedTextField(Tel);  
        telefone_cel = new JFormattedTextField(Tel_cel); 
        cpf = new JFormattedTextField(CPF);
        dat = new JFormattedTextField(Dat);
        cep = new JFormattedTextField(CEP);
                     
        Tel.setValidCharacters("[telefone removido]");
        Tel_cel.setValidCharacters("[telefone removido]"); 
        CPF.setValidCharacters("[telefone removido]");         
        Dat.setValidCharacters("[telefone removido]");
        CEP.setValidCharacters("[telefone removido]");
                    
        telefone.setColumns(9);
        telefone_cel.setColumns(9);
        cpf.setColumns(10);  
        dat.setColumns(7);
        cep.setColumns(9);           
                
        String sexo[] = {"M","F"};
    	combo = new JComboBox(sexo);
   	 	combo.setBackground(Color.white);
    	combo.setForeground(Color.black);
    	combo.addItemListener(new ItemListener(){
      	public void itemStateChanged(ItemEvent ie){
        String str = (String)combo.getSelectedItem();
      }
    });
    
    	String uf[] = {"AC","AL","AP","AM","BA","CE","DF","ES","GO","MA","MT","MS","MG","PA","PB","PR","PE","PI","RR","RO","RJ","RN","RS","SC","SP","SE","TO"};
    	combo_2 = new JComboBox(uf);
   	 	combo_2.setBackground(Color.white);
    	combo_2.setForeground(Color.black);
    	combo_2.addItemListener(new ItemListener(){
      	public void itemStateChanged(ItemEvent ie){
        String str = (String)combo_2.getSelectedItem();
      }
    });
        String modalidade[] = {"1","2","3","4","5","6","7","8","9"};
    	combo_3 = new JComboBox(modalidade);
   	 	combo_3.setBackground(Color.white);
    	combo_3.setForeground(Color.black);
    	combo_3.addItemListener(new ItemListener(){
      	public void itemStateChanged(ItemEvent ie){
        String str = (String)combo_3.getSelectedItem();
      }
    });
        String planos[] = {"3","6","12"};
    	combo_4 = new JComboBox(planos);
   	 	combo_4.setBackground(Color.white);
    	combo_4.setForeground(Color.black);
    	combo_4.addItemListener(new ItemListener(){
      	public void itemStateChanged(ItemEvent ie){
        String str = (String)combo_4.getSelectedItem();
      }
    });
    	b1 = new JButton("Novo");
    	b2 = new JButton("Limpar");
    	b3 = new JButton("Salvar");  
    	b4 = new JButton("Deletar"); 
    	  	   	  	
        l1 = new JLabel ("Matrícula nº:");
    	l2 = new JLabel ("Nome:");
    	l3 = new JLabel ("CPF:");
  		l4 = new JLabel ("Sexo:");
    	l5 = new JLabel ("Nascimento");
    	l6 = new JLabel ("tel residencial:");
    	l7 = new JLabel ("tel celular:");
    	l8 = new JLabel ("Endereço:");
    	l9 = new JLabel ("nº");
    	l10 = new JLabel ("Bairro:");
    	l11 = new JLabel("Cidade:");
    	l12 = new JLabel("Estado:");
    	l13 = new JLabel ("CEP:");
    	l14 = new JLabel ("Data da matricula");
    	SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");
    	l15 = new JLabel ("Modalidade:");
    	l16 = new JLabel ("Plano meses:");    	    	
    	c1 = new JTextField (5);
    //	c1.setEditable(false); // anula a entrada de dados
    	c2 = new JTextField (36);
    	c3 = new JTextField (15);
    	c5 = new JTextField (10);
    	c6 = new JTextField (10); 
    	c7 = new JTextField (10);
    	c8 = new JTextField (31);
    	c9 = new JTextField (5);
    	c10 = new JTextField (17);   	
    	c11	= new JTextField (19); 
    	c12 = new JTextField (10);    	
    	c14 = new JTextField (5);
    	c14.setText(data.format(Calendar.getInstance().getTime()));  

    	JTextField [] vetTF = { c1, c2, c3, c5, c6, c7, c8, c9, c10, c11, c12, cpf, dat, telefone, telefone_cel, cep};
    	
    	p1.add(l1);
    	p1.add(c1);
    	p1.add(l2);
    	p1.add(c2);
    	p1.add(l3);
    	p1.add(cpf);    	
    	p1.add(l4);
    	p1.add(combo);
    	p1.add(l5);
    	p1.add(dat);
    	p1.add(l6);
    	p1.add(telefone);
    	p1.add(l7);
    	p1.add(telefone_cel);
    	p1.add(l8);
    	p1.add(c8);
    	p1.add(l9); 
    	p1.add(c9);   
    	p1.add(l10);
    	p1.add(c10);
    	p1.add(l11);
    	p1.add(c11);    	
    	p1.add(l12);
    	p1.add(combo_2);
    	p1.add(l13);
    	p1.add(cep);     	   	    	
    	p2.add(l14);
    	p2.add(c14);
    	p2.add(l15);
    	p2.add(combo_3);
    	p2.add(l16);
    	p2.add(combo_4);     	   	 
    	p1.add(p2);    	    	
    	p3.add(b1);
    	p3.add(b2);
    	p3.add(b3);
    	p3.add(b4);
    	p1.add(p3);    	  
    	  	    	    	
    	b1.setForeground(Color.blue);
    	b2.setForeground(Color.blue);
    	b3.setForeground(Color.blue);
    	b4.setForeground(Color.red);  	
    	tba = new TratarBotoesTelaAluno(b1,b2,b3,b4, vetTF); 
    	b1.addActionListener(tba);
		b2.addActionListener(tba);
		b3.addActionListener(tba); 
		b4.addActionListener(tba);
		this.setContentPane(p1);
		 
		setSize(600,360);
		setResizable(false);
		setLocationRelativeTo(null);
	}
	class TratarBotoesTelaAluno implements ActionListener{
	private JButton b1, b2, b3, b4;
	private JTextField [] vetC;
	
	public TratarBotoesTelaAluno(JButton ba, JButton bb, JButton bc, JButton bd, JTextField [] vetCampos){
		b1 = ba;
		b2 = bb;
		b3 = bc;
		b4 = bd;	
		vetC = vetCampos;
	}	
	 public void actionPerformed(ActionEvent acao){    
        if(acao.getSource() == b1) {
        	for(JTextField campo : vetC)
            campo.setText("");
            System.out.println("Novo aberto");
            } else {
            	if(acao.getSource() == b2) {
            		for(JTextField campo : vetC)
            		campo.setText("");
            		System.out.println("Formulario limpo");
            		}else{
            			if(acao.getSource() == b3){            	
            				new ConexaoAccess();

            				 /*Statement st = conexao.createStatement();   
                             executeUpdate("INSERT INTO Aluno (Matricula, nome) VALUES ('"+   
                             c1.getText() +"','"+   
                             c2.getText() +"')");*/
            				
            				// salvar na tabela aluno
            				
                		    System.out.println("Salvando no banco de dados");
                		    JOptionPane.showMessageDialog(null,"Conexão Estabelecida");
                		    }else{
                		    	if(acao.getSource() == b4){
                		        			System.out.println("Dados deletados.");
                		        			
                		        			// deletar dados na tabela aluno
                		        			
                		        			JOptionPane.showMessageDialog(null,"DADOS DELETADOS");
                		        			}
                		        		}
                		       	}  	
                	      }    
               	}
     	} 
   }
Criado 11 de junho de 2010
Ultima resposta 12 de jun. de 2010
Respostas 2
Participantes 2