[Urgente] Problema para conectar NetBeans com Access

10 respostas
F

Olá galera, eu preciso fazer um programa para fluxo de caixa em que na qual os dados seram salvos no access, porem naum to conseguindo fazer a conexão com o access, está dando alguns erros...

janela principal...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class fluxo_de_caixa extends javax.swing.JFrame {

private Connection conexao;
private Statement comando;
private static ResultSet resultado;
private static String driver,url;


     
    /** Creates new form fluxo_de_caixa */
        public fluxo_de_caixa() {
        initComponents();
        driver="sun.jdbc.odbc.JdbcOdbcDriver";
	url="jdbc:odbc:BD";
        setTitle("Navegando no Banco de Dados");
	setVisible(true);
	pack();
    }

    /** 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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        Saída = new javax.swing.JButton();
        Entrada = new javax.swing.JButton();
        RelatórioMensal = new javax.swing.JButton();
        RelatórioAnual = new javax.swing.JButton();
        Sair = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        Arquivo = new javax.swing.JMenu();
        SaídadeCaixaMenu = new javax.swing.JMenuItem();
        EntradadeCaixaMenu = new javax.swing.JMenuItem();
        RelatórioMensalMenu = new javax.swing.JMenuItem();
        RelatórioAnualMenu = new javax.swing.JMenuItem();
        SairMenu = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("FluxCa");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        Saída.setText("Saída");
        Saída.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaídaActionPerformed(evt);
            }
        });

        Entrada.setText("Entrada");
        Entrada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EntradaActionPerformed(evt);
            }
        });

        RelatórioMensal.setText("Relatório Mensal");
        RelatórioMensal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RelatórioMensalActionPerformed(evt);
            }
        });

        RelatórioAnual.setText("Relatório Anual");
        RelatórioAnual.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RelatórioAnualActionPerformed(evt);
            }
        });

        Sair.setText("Sair");
        Sair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SairActionPerformed(evt);
            }
        });

        Arquivo.setText("Arquivo");

        SaídadeCaixaMenu.setText("Saída de Caixa");
        SaídadeCaixaMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaídadeCaixaMenuActionPerformed(evt);
            }
        });
        Arquivo.add(SaídadeCaixaMenu);

        EntradadeCaixaMenu.setText("Entrada de Caixa");
        EntradadeCaixaMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EntradadeCaixaMenuActionPerformed(evt);
            }
        });
        Arquivo.add(EntradadeCaixaMenu);

        RelatórioMensalMenu.setText("Relatório Mensal");
        RelatórioMensalMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RelatórioMensalMenuActionPerformed(evt);
            }
        });
        Arquivo.add(RelatórioMensalMenu);

        RelatórioAnualMenu.setText("Relatório anual");
        RelatórioAnualMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RelatórioAnualMenuActionPerformed(evt);
            }
        });
        Arquivo.add(RelatórioAnualMenu);

        SairMenu.setText("Sair");
        SairMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SairMenuActionPerformed(evt);
            }
        });
        Arquivo.add(SairMenu);

        jMenuBar1.add(Arquivo);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(RelatórioAnual, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
                    .addComponent(RelatórioMensal, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Saída, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
                        .addComponent(Entrada)))
                .addGap(28, 28, 28))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(113, Short.MAX_VALUE)
                .addComponent(Sair)
                .addGap(111, 111, 111))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Saída)
                    .addComponent(Entrada))
                .addGap(33, 33, 33)
                .addComponent(RelatórioMensal)
                .addGap(35, 35, 35)
                .addComponent(RelatórioAnual)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addComponent(Sair)
                .addGap(25, 25, 25))
        );

        getAccessibleContext().setAccessibleDescription("Fluxo de Caixa");

        pack();
    }// </editor-fold>                        

    private void SairActionPerformed(java.awt.event.ActionEvent evt) {                                     
        desconecta();
        this.setDefaultCloseOperation(fluxo_de_caixa.DISPOSE_ON_CLOSE);
        this.setVisible(false);
        this.dispose();        // TODO add your handling code here:
    }                                    

    private void SairMenuActionPerformed(java.awt.event.ActionEvent evt) {                                         
        desconecta();
        this.setDefaultCloseOperation(fluxo_de_caixa.DISPOSE_ON_CLOSE);
        this.setVisible(false);
        this.dispose();  // TODO add your handling code here:
    }                                        

    private void SaídaActionPerformed(java.awt.event.ActionEvent evt) {                                      
        new Saída().setVisible(true);// TODO add your handling code here:
    }                                     

    private void EntradaActionPerformed(java.awt.event.ActionEvent evt) {                                        
        new Entrada().setVisible(true);// TODO add your handling code here:
    }                                       

    private void RelatórioMensalActionPerformed(java.awt.event.ActionEvent evt) {                                                
        new RelatórioMensal().setVisible(true);// TODO add your handling code here:
    }                                               

    private void RelatórioAnualActionPerformed(java.awt.event.ActionEvent evt) {                                               
        new RelatórioAnual().setVisible(true);// TODO add your handling code here:
    }                                              

    private void SaídadeCaixaMenuActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        new Saída().setVisible(true);// TODO add your handling code here:
    }                                                

    private void EntradadeCaixaMenuActionPerformed(java.awt.event.ActionEvent evt) {                                                   
        new Entrada().setVisible(true);// TODO add your handling code here:
    }                                                  

    private void RelatórioMensalMenuActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        new RelatórioMensal().setVisible(true);// TODO add your handling code here:
    }                                                   

    private void RelatórioAnualMenuActionPerformed(java.awt.event.ActionEvent evt) {                                                   
        new RelatórioAnual().setVisible(true);// TODO add your handling code here:
    }                                                  




    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new fluxo_de_caixa().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JMenu Arquivo;
    private javax.swing.JButton Entrada;
    private javax.swing.JMenuItem EntradadeCaixaMenu;
    private javax.swing.JButton RelatórioAnual;
    private javax.swing.JMenuItem RelatórioAnualMenu;
    private javax.swing.JButton RelatórioMensal;
    private javax.swing.JMenuItem RelatórioMensalMenu;
    private javax.swing.JButton Sair;
    private javax.swing.JMenuItem SairMenu;
    private javax.swing.JButton Saída;
    private javax.swing.JMenuItem SaídadeCaixaMenu;
    private javax.swing.JMenuBar jMenuBar1;
    // End of variables declaration                   

   public void conecta(){
	try{
	    Class.forName(driver);
	    conexao=DriverManager.getConnection(url,"","");

	    comando=conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
	    resultado=comando.executeQuery(access);
	    System.out.println("Conexão executada com sucesso");
	   // atualizaCampos();
            
            ResultSet rs = comando.executeQuery("SELECT * FROM IC");
	 while (rs.next())
            {
            System.out.println("Nome: " + rs.getString("nome"));
            }

	}
	catch(SQLException AccessExc){
	    System.out.println("Erro de SQL8!");
	}
	catch(ClassNotFoundException exc){
	    System.out.println("Classe não encontrada!");
	}


}




    public  void desconecta(){
	try{
	conexao.close();
	}
	catch(SQLException SqlExc){
		System.out.println("Erro de SQL3!");
	}
}

}
Conecta o banco de dados
import java.sql.*;
public class TestaConexao{
   private String driver,url;
   private Connection conexao;
   public TestaConexao(){
		driver="sun.jdbc.odbc.JdbcOdbcDriver";
		url="jdbc:odbc:BD";  // nome dado ao banco
		conecta(driver,url);
	}
	public void conecta(String driver, String url){
		try{
		// carrega o driver da ponte jdbc-odbc
		Class.forName(driver);
		// abre conexao com o banco de dados
		conexao=DriverManager.getConnection(url,"","");
		System.out.println("Conexão executada com sucesso");
		conexao.close();
		}
	catch(SQLException SqlExc){
		System.out.println("Erro de SQL!");
	}

	catch(ClassNotFoundException exc){
		System.out.println("Classe não encontrada!");
	}
	}
	public  static void main(String args[]){
		TestaConexao ins=new TestaConexao();
	}
}
Testa DML import java.sql.*;
public class TestaDML{
   private static String driver,url;
   private Connection conexao;
   private Statement comando;
   private static ResultSet resultado;
   public TestaDML(){
        driver="sun.jdbc.odbc.JdbcOdbcDriver";
	 url="jdbc:odbc:BD";    //nome do banco
 }
public void conecta(){
	try{
	// carrega o driver da ponte jdbc-odbc
	   Class.forName(driver);
	// abre conexao com o banco de dados
	   conexao=DriverManager.getConnection(url,"","");
	   System.out.println("Conexão executada com sucesso");
	}
	catch(SQLException SqlExc){
		System.out.println("Erro de SQL!");
	}
	catch(ClassNotFoundException exc){
		System.out.println("Classe não encontrada!");
	}
	}
//public void listaDados (){
//	   String sql="select * from CD";
//		try{
//		comando=conexao.createStatement();
//		resultado=comando.executeQuery(sql);
//		while(resultado.next()){
//			String nome  =resultado.getString(?nome");
//			String datacompra  =resultado.getString(?datacompra");
//			String localcompra  =resultado.getString(?localcompra");
//			String valor  =resultado.getString(?valor");
//			System.out.println(?Nome: "+nome+...);
  // 			}
//		}
//		catch(SQLException SqlExc){
//			System.out.println("Erro de SQL!");
//		} }
public void desconecta(){
	try{
		conexao.close();
		}
	catch(SQLException SqlExc){
		System.out.println("Erro de SQL!");
	}
	}
	public  static void main(String args[]){
		TestaDML tdml=new TestaDML();
		tdml.conecta();
//	    	tdml.listaDados();
	    	tdml.desconecta();
	}
}

Eu utilizo o NetBeans 6.7.1, o banco de dados se xama IC e o drive se xama BD...

Por favor, preciso disso urgentemente, pois tenho que apresentar esse programa dia 30/11

10 Respostas

F

eu fiz 2 modificações no programa principal

uma delas, troquei no conecta isso…

comando=conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); resultado=comando.executeQuery(access); System.out.println("Conexão executada com sucesso"); // atualizaCampos();

por isso…

comando=conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); //resultado=comando.executeQuery(access); System.out.println("Conexão executada com sucesso"); // atualizaCampos();

e a outra troquei isso…

public fluxo_de_caixa() { initComponents(); driver="sun.jdbc.odbc.JdbcOdbcDriver"; url="jdbc:odbc:BD"; setTitle("Navegando no Banco de Dados"); setVisible(true); pack(); }

por isso…

public fluxo_de_caixa() { initComponents(); driver="sun.jdbc.odbc.JdbcOdbcDriver"; url="jdbc:odbc:BD"; setTitle("Navegando no Banco de Dados"); setVisible(true); conecta(); pack(); }

e pelo - os erros que estavam dando relacionados ao desconecta sumiram, porem agora está dando um erro dentro do conecta e eu naum sei oq pode ser…

Guinter

Opa! na classe conecta vc pega a conexão e logo em baixo vc fecha

public void conecta(String driver, String url){  
         try{  
         // carrega o driver da ponte jdbc-odbc  
         Class.forName(driver);  
         // abre conexao com o banco de dados  
         conexao=DriverManager.getConnection(url,"","");  
         System.out.println("Conexão executada com sucesso");  
         conexao.close();  //aqui
         }
F

esse conecta q vc se refere eh no TestaConexao, e onde está dando erro eh no conecta da janela principal…

F

outra dúvida, depois de conectar ao access, eu posso utilizar comando sql para fazer inserção, linstagem de dados, etc.???

VagnerChines

Claro k sim.

F

ainda estou com problema no conecta da janela principal
:?: :?: :?:

F

eu axo q resolvi o erro da conexão, pelo - naum esta apontando mais nenhum erro, porem agora estou com uma duvida...

q nem, quando o programa eh inicializado automaticamente ele conecta no banco de dados, e na janela principal soh contem botões que abrem outras janelas, uma delas eh pra cadastro de dados, e eu gostaria de saber se nessa janela de cadastro de dados eu tenho q conectar novamente no banco de dados ou tem como utilizar essa msm conexão, pois naum to conseguindo ter acesso ao banco por essa janela, e gostaria de saber como que eu poderia fazer para cadastrar os dados, os capos são Colaborador, Item, Valor, Local, Data, etc..., se eu tenho que salvar todos os dados em cada campo da tabela ao mesmo tempo ou se eh melhor salvar separadamente, e como que faz isso, pois naum estou conseguindo fazer isso

a seguir segue o código da janela...
import java.sql.*;
import javax.swing.JOptionPane;


public class Saída extends javax.swing.JFrame {

private Connection con;
private Statement stmt;
private static ResultSet resultado;
private static String driver="sun.jdbc.odbc.JdbcOdbcDriver",url="jdbc:odbc:BD";

    /** Creates new form Saída */
    public Saída() {
        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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        Colaborador = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        Item = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        Valor = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        Categoria = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        Referência = new javax.swing.JComboBox();
        Salvar = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        Data = new javax.swing.JFormattedTextField();
        Local = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        Arquivo = new javax.swing.JMenu();
        SalvarMenu = new javax.swing.JMenuItem();
        SairMenu = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Saída - FluxCa");

        Colaborador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ColaboradorActionPerformed(evt);
            }
        });

        jLabel1.setText("Colaborador(a)");

        Item.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ItemActionPerformed(evt);
            }
        });

        jLabel2.setText("Item");

        jLabel3.setText("Data");

        Valor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("0.00"))));
        Valor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ValorActionPerformed(evt);
            }
        });

        jLabel4.setText("Valor");

        Categoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "AEC", "AERE", "ALG", "ALM", "BRD", "BUS", "CAP", "CART", "COMB", "COMC", "COND", "CONG", "CONS", "COR", "COS", "DIV", "EPEL", "EQP", "ESC", "EST", "GRA", "HPD", "IMP", "INT", "LOG", "LPZ", "LUZ", "MAN-G", "MAN-V", "MLT", "MOT", "PED", "SEG", "TAX", "TELC", "TELF", "BMM" }));

        jLabel5.setText("Categoria");

        jLabel6.setText("Referência");

        Referência.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ADM-D", "ADM-E", "ADM-L", "BAND", "CREDE", "DES-EQ", "EACAO", "ESCL", "FB", "IND", "ORG-IC", "PFP", "PIL", "PROSP", "RH", "ROF", "UP", "VOT", "VPV" }));
        Referência.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ReferênciaActionPerformed(evt);
            }
        });

        Salvar.setText("Salvar");
        Salvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SalvarActionPerformed(evt);
            }
        });

        jLabel7.setText("R$");

        Data.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));
        Data.setText("dd/mm/AAAA");
        Data.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DataActionPerformed(evt);
            }
        });

        Local.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LocalActionPerformed(evt);
            }
        });

        jLabel10.setText("Local");

        Arquivo.setText("Arquivo");

        SalvarMenu.setText("Salvar");
        Arquivo.add(SalvarMenu);

        SairMenu.setText("Sair");
        SairMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SairMenuActionPerformed(evt);
            }
        });
        Arquivo.add(SairMenu);

        jMenuBar1.add(Arquivo);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(Item, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel10)
                                    .addComponent(Local, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(Colaborador))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(Categoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(Data, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(51, 51, 51)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel4)
                            .addComponent(Referência, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(Valor, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(61, 61, 61))))
            .addGroup(layout.createSequentialGroup()
                .addGap(134, 134, 134)
                .addComponent(Salvar)
                .addContainerGap(172, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Colaborador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Item, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Local, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Data, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Categoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(Valor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Referência, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                .addComponent(Salvar)
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>

    private void ColaboradorActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void SairMenuActionPerformed(java.awt.event.ActionEvent evt) {                                         
        this.setDefaultCloseOperation(Saída.DISPOSE_ON_CLOSE);
        this.setVisible(false);
        this.dispose();// TODO add your handling code here:
    }                                        

    private void ReferênciaActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void SalvarActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                      

    private void ItemActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void LocalActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void DataActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void ValorActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Saída().setVisible(true);
                try{
                con = DriverManager.getConnection(url,"","");
                stmt = con.createStatement();
                }
                catch (SQLException sqle)
	        {
	            JOptionPane.showMessageDialog(null, "Problema ao conectar!");
	            System.exit(0);
	        }
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JMenu Arquivo;
    private javax.swing.JComboBox Categoria;
    private javax.swing.JTextField Colaborador;
    private javax.swing.JFormattedTextField Data;
    private javax.swing.JTextField Item;
    private javax.swing.JTextField Local;
    private javax.swing.JComboBox Referência;
    private javax.swing.JMenuItem SairMenu;
    private javax.swing.JButton Salvar;
    private javax.swing.JMenuItem SalvarMenu;
    private javax.swing.JFormattedTextField Valor;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JMenuBar jMenuBar1;
    // End of variables declaration

}
F

eu fiz algumas modificações na janela Saída, porém agora está dando erro na hora de salvar, oq pode ser???

import java.io.DataInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


public class Saída extends javax.swing.JFrame {

private Connection con;
private Statement stmt;
private static ResultSet resultado;
private static String driver="sun.jdbc.odbc.JdbcOdbcDriver",url="jdbc:odbc:BD";
private DataInputStream dado;
private String colaborador, item, local;

    /** Creates new form Saída */
    public Saída() {
        driver="sun.jdbc.odbc.JdbcOdbcDriver";
	url="jdbc:odbc:BD";
        setTitle("Saída de Caixa");
	setVisible(true);
	Conectar();
        pack();
        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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        Colaborador = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        Item = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        Valor = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        Categoria = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        Referência = new javax.swing.JComboBox();
        Salvar = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        Data = new javax.swing.JFormattedTextField();
        Local = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        Sair = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        Arquivo = new javax.swing.JMenu();
        SalvarMenu = new javax.swing.JMenuItem();
        SairMenu = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Saída - FluxCa");

        Colaborador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ColaboradorActionPerformed(evt);
            }
        });

        jLabel1.setText("Colaborador(a)");

        Item.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ItemActionPerformed(evt);
            }
        });

        jLabel2.setText("Item");

        jLabel3.setText("Data");

        Valor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("0.00"))));
        Valor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ValorActionPerformed(evt);
            }
        });

        jLabel4.setText("Valor");

        Categoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "AEC", "AERE", "ALG", "ALM", "BRD", "BUS", "CAP", "CART", "COMB", "COMC", "COND", "CONG", "CONS", "COR", "COS", "DIV", "EPEL", "EQP", "ESC", "EST", "GRA", "HPD", "IMP", "INT", "LOG", "LPZ", "LUZ", "MAN-G", "MAN-V", "MLT", "MOT", "PED", "SEG", "TAX", "TELC", "TELF", "BMM" }));

        jLabel5.setText("Categoria");

        jLabel6.setText("Referência");

        Referência.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ADM-D", "ADM-E", "ADM-L", "BAND", "CREDE", "DES-EQ", "EACAO", "ESCL", "FB", "IND", "ORG-IC", "PFP", "PIL", "PROSP", "RH", "ROF", "UP", "VOT", "VPV" }));
        Referência.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ReferênciaActionPerformed(evt);
            }
        });

        Salvar.setText("Salvar");
        Salvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SalvarActionPerformed(evt);
            }
        });

        jLabel7.setText("R$");

        Data.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));
        Data.setText("dd/mm/AAAA");
        Data.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DataActionPerformed(evt);
            }
        });

        Local.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LocalActionPerformed(evt);
            }
        });

        jLabel10.setText("Local");

        Sair.setText("Sair");
        Sair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SairActionPerformed(evt);
            }
        });

        Arquivo.setText("Arquivo");

        SalvarMenu.setText("Salvar");
        Arquivo.add(SalvarMenu);

        SairMenu.setText("Sair");
        SairMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SairMenuActionPerformed(evt);
            }
        });
        Arquivo.add(SairMenu);

        jMenuBar1.add(Arquivo);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel1)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(Item, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2)
                                .addComponent(Salvar, javax.swing.GroupLayout.Alignment.TRAILING))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(18, 18, 18)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel10)
                                        .addComponent(Local, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(40, 40, 40)
                                    .addComponent(Sair))))
                        .addComponent(Colaborador))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(Categoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(Data, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(51, 51, 51)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel4)
                            .addComponent(Referência, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(Valor, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(61, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Colaborador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Item, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Local, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Data, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Categoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(Valor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Referência, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Salvar)
                    .addComponent(Sair))
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>                        

    private void ColaboradorActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        try{
			dado=new DataInputStream(System.in);
			colaborador=String.valueOf(dado.readLine());
            try {
                System.out.println("Colaborador= " + resultado.getString("Colaborador"));
            } catch (SQLException ex) {
                Logger.getLogger(Saída.class.getName()).log(Level.SEVERE, null, ex);
            }
                        }
		catch(IOException e)
		  {System.out.println("Erro na entrada de dados");}
    }                                           

    private void SairMenuActionPerformed(java.awt.event.ActionEvent evt) {                                         
        desconecta();
        this.setDefaultCloseOperation(Saída.DISPOSE_ON_CLOSE);
        this.setVisible(false);
        this.dispose();// TODO add your handling code here:
    }                                        

    private void ReferênciaActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void SalvarActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        try{
	     String sql="insert into IC.Saída de Caixa values('"+Colaborador.getText()+"','"+Item.getText()+"','"+Local.getText()+"');";
                        stmt.executeUpdate(sql);
			System.out.println("Salvo!");

		}
		catch(SQLException SqlExc){
			System.out.println("Erro de SQL6!");
		}
    }                                      

    private void ItemActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
        try{
			dado=new DataInputStream(System.in);
			item=String.valueOf(dado.readLine());
                        System.out.println("item");
                        }
		catch(IOException e)
		  {System.out.println("Erro na entrada de dados");}

    }                                    

    private void LocalActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        try{
			dado=new DataInputStream(System.in);
			local=String.valueOf(dado.readLine());
                        System.out.println("local");
                        }
		catch(IOException e)
		  {System.out.println("Erro na entrada de dados");}
    }                                     

    private void DataActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
    }                                    

    private void ValorActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    private void SairActionPerformed(java.awt.event.ActionEvent evt) {                                     
        desconecta();
        this.setDefaultCloseOperation(Saída.DISPOSE_ON_CLOSE);
        this.setVisible(false);
        this.dispose();
        // TODO add your handling code here:
    }                                    

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Saída().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JMenu Arquivo;
    private javax.swing.JComboBox Categoria;
    private javax.swing.JTextField Colaborador;
    private javax.swing.JFormattedTextField Data;
    private javax.swing.JTextField Item;
    private javax.swing.JTextField Local;
    private javax.swing.JComboBox Referência;
    private javax.swing.JButton Sair;
    private javax.swing.JMenuItem SairMenu;
    private javax.swing.JButton Salvar;
    private javax.swing.JMenuItem SalvarMenu;
    private javax.swing.JFormattedTextField Valor;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JMenuBar jMenuBar1;
    // End of variables declaration                   

    public void Conectar()
	    {
	        System.out.println("Preparando para iniciar a conexão com o BD;");

	        try
	        {
	            /* Tenta se conectar ao Driver */
	            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	        }
	        catch (ClassNotFoundException e)
	        {
	            JOptionPane.showMessageDialog(null, "Impossível carregar o Driver.");
	            System.exit(0);
	        }
	        try
	        {
	            /* nomedobanco é o nome que você deu anteriormente ao seu alias */
	            con = DriverManager.getConnection("jdbc:odbc:BD");
	            stmt = con.createStatement();
	        }
	        catch (SQLException sqle)
	        {
	            JOptionPane.showMessageDialog(null, "Problema ao conectar!");
	            System.exit(0);
	        }

	        System.out.println("Conectado com sucesso!");
	    }




    public  void desconecta(){
	System.out.println("Desconectando!");
        try{
	con.close();
	}
	catch(SQLException SqlExc){
		System.out.println("Erro de SQL3!");
	}
}



}
F

poh galera, alguem me ajuda ai vai, por favor…

thundercas

flp_bn,

Você deve separar tudo em processos… Se você está salvando os dados de um cliente, salve-os todos de uma vez… Se vai salvar os dados do cliente e, em seguida, atualizar a tabela que guarda o total de clientes, faça os 2 separadamente, pois são 2 processos distintos, OK??

Em relação a usar a mesma conexão ou iniciar uma nova, seguirá a mesma idéia citada acima. Se for o mesmo processo, utilize a mesma conexão (se for um loop para atualizar o cadastro de clientes, por exemplo).
Se o usuário incluir um novo cliente, você abre a conexão, faz o que for necessário e fecha em seguida… Se, após cadastrar o cliente o usuário deseja consultar o cadastro deste cliente, você abre uma nova conexão e fecha em seguida… OK?? Isso evita sobrecarga do servidor e banco…

abs

Criado 24 de novembro de 2009
Ultima resposta 1 de dez. de 2009
Respostas 10
Participantes 4