Ajuda para salvar no access

13 respostas
DANIEL35
Boa tarde a todos, estou precisando salvar meus dados de entrada no access, mas estou encontrando diversas dificuldades. Minha conexão está correta. Ao digitar o comando:
public int adicionaAluno(Aluno aluno) throws SQLException, ClassNotFoundException{
            				String sql = "insert into aluno (Cod_matricula, Nome, CPF, Sexo, Nascimento, Tel_residencial, Tel_celular, Endereço, nº, Bairro) values (?,?,?,?,?,?,?,?,?,?)";
							executeCommand(sql, aluno.getCod_matricula(), aluno.getNome(), aluno.getCPF(), aluno.getSexo(), aluno.getNascimento(), aluno.getTel_residencial(), aluno.getTel_celular(), aluno.getEndereço(), aluno.getNº(), aluno.getBairro());
							return aluno.getCod_matricula();
							}
acontece vários erros: ilegal start of expression... expected";".... not a statement Como poderia inserir as informações na tabela aluno? Essa tabela está exatamente com esses campos acima. meus textFields e labels também, vejam:
..........
........	
b1 = new JButton("Novo");
    	b2 = new JButton("Limpar");
    	b3 = new JButton("Salvar");  
    	b4 = new JButton("Deletar"); 
    	  	   	  	
        l1 = new JLabel ("Cod_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:");  
............
.........
 class TratarBotoesTelaAluno implements ActionListener{
	private JButton b1, b2, b3, b4;
...
.....

13 Respostas

Mikhas

Ja tentou adicionar um “;” no fim do comando sql ?

Como desenvolvedor, eu aconselharia você a não utilizar o Access. Como alternativa você pode usar o HyperSQL (HSQLDB) que você nem precisa instalar nada no cliente e é super simples de usar.

DANIEL35

onde precisamente você fala para colocar o “;” ? Todos os comandos estão com o sinal.

Mikhas

no fim…

String sql = “insert into aluno (Cod_matricula, Nome, CPF, Sexo, Nascimento, Tel_residencial, Tel_celular, Endereço, nº, Bairro) values (?,?,?,?,?,?,?,?,?,?)[color=red];[/color]”;

DANIEL35

Continua com os mesmos erros. O que será que estou fazendo de tão grave?

Mikhas

Usando o Access

DANIEL35

Nesse outro banco de dados que você disse, como ficaria?

viniciusgundim

Olá amigo,
Manda todo o código dessa classe.

DANIEL35
Correto, o código da classe "CadastroAluno" vai aí:
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 ("Cod_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();
            				
            			/*public int adicionaAluno(Aluno aluno) throws SQLException, ClassNotFoundException{
            				String sql = "insert into aluno (Cod_matricula, Nome, CPF, Sexo, Nascimento, Tel_residencial, Tel_celular, Endereço, nº, Bairro) values (?,?,?,?,?,?,?,?,?,?)";
							executeCommand(sql, aluno.getCod_matricula(), aluno.getNome(), aluno.getCPF(), aluno.getSexo(), aluno.getNascimento(), aluno.getTel_residencial(), aluno.getTel_celular(), aluno.getEndereço(), aluno.getNº(), aluno.getBairro());
							return aluno.getCod_matricula();
							}*/	
            				
            				
            				// 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");
                		        			}
                		        		}
                		       	}  	
                	      }    
               	}
     	} 
   }
DANIEL35

Conseguiu perceber quais foram os meus erros?

S

No seu codigo sua string de query está em uma unica linha?
Tenta usar o statement ao inves do preparedstatement, o pstmt as vezes não funciona legal, depende muito do driver que vc usou.

viniciusgundim

É o seguinte kra, na sua query vc tem que fazer o seguinte:

String sql = "insert into aluno (Cod_matricula, Nome, CPF, Sexo, Nascimento, Tel_residencial, Tel_celular, Endereço, nº, Bairro) values ('"+jtf_cod_matricula.getText+"')";

e assim segue pegando cada valor, mais ai vc passou os values assim code[/code]

não intend isso!!!

ai depois que criar sua query é só chama-lá:

con.execultesql(sql);
pmlm

viniciusgundim:
É o seguinte kra, na sua query vc tem que fazer o seguinte:

String sql = "insert into aluno (Cod_matricula, Nome, CPF, Sexo, Nascimento, Tel_residencial, Tel_celular, Endereço, nº, Bairro) values ('"+jtf_cod_matricula.getText+"')";

e assim segue pegando cada valor, mais ai vc passou os values assim code[/code]

não intend isso!!!

ai depois que criar sua query é só chama-lá:

con.execultesql(sql);

ERRADO!

Ele usa (como se deve usar) PreparedStatement.

O problema aqui é que crias um método dentro de outro método…

public int adicionaAluno… isto já está dentro de um método, não podes criar um método dentro de outro.

S

viniciusgundim:
É o seguinte kra, na sua query vc tem que fazer o seguinte:

String sql = "insert into aluno (Cod_matricula, Nome, CPF, Sexo, Nascimento, Tel_residencial, Tel_celular, Endereço, nº, Bairro) values ('"+jtf_cod_matricula.getText+"')";

e assim segue pegando cada valor, mais ai vc passou os values assim code[/code]

não intend isso!!!

ai depois que criar sua query é só chama-lá:

con.execultesql(sql);


Vc usa essas ‘?’ quando usa o preparedstatement cara. Essa parte ta certinha.

Putz vi só o primeiro post, não tinha visto que ele escrevia um metodo dentro do outro…

Criado 17 de junho de 2010
Ultima resposta 18 de jun. de 2010
Respostas 13
Participantes 5