Fazendo um Select apartir de uma interface Java

2 respostas
D

Bom dia a todos,

Acredito que a minha duvida é bem simples, estou iniciando agora com BD e estou com dificuldades.
Eu tenho uma aplicação em java, tenho por exemplo, um botão PESQUISA, então quando eu clicar nele gostaria que ele me retorna-se o resultado do SELECT abaixo:

Alguem tem algum exemplo de como fazer isso em java?

Obrigado pela ajuda

Dieison Grumovski

2 Respostas

T
De uma olhada no codigo abaixo
public static List obterPorListagem( ) throws SQLException {
			PreparedStatement stmt = null;
			ResultSet rs = null;
			
			ArrayList lista = new ArrayList();
			
			try{
				String sql = "SELECT cd_moto, sum(vl_servico)FROM MOTO_OFICINA_MECANICA WHERE (dt_servico between (SELECT date 'now' - integer '30') AND (SELECT date 'now')) GROUP BY cd_moto";
				stmt = con.prepareStatement( sql );
				
				rs = stmt.executeQuery();
				
				while( rs.next() ) {
					lista.add( new MOTO_OFICINA_MECANICA( rs ) );
				}
				return lista;
				
			} finally {
				rs.close();
				stmt..close();
			}
		}
H

Cara, você pode também fazer da seguinte forma:

public class exemplo{
   public static Vector select(){		
		Vector results = new Vector();
		ResultSet rs = null;
		Statement stmt = null;
		
		try {         
			String sql = "SELECT cd_moto, sum(vl_servico)FROM MOTO_OFICINA_MECANICA WHERE (dt_servico between (SELECT date 'now' 					- integer '30') AND (SELECT date 'now')) GROUP BY cd_moto";
            stmt = con.prepareStatement( sql );            
            rs = stmt.executeQuery();          
		}
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Exception");
			e.printStackTrace();
		}

		try {
			while (rs.next()) {
				String cd_moto = rs.getStirng("cd_moto");
				double vl_servico = rs.getDouble("vl_servico");
				results.add(0, new String(cd_moto));
				results.add(1, new Double(vl_servico));					
				return results;
			}
		} catch (SQLException e1) {         
			e1.printStackTrace();
		}


		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}         
		}

		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		try {
			con.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}	
		return null;
	}
   }
}

Onde cada campo do vetor de resultado vai conter um dos campos que você quer.
Para fazer o botão que você quer, faça:

public class NovoJFrame extends javax.swing.JFrame {
    
    public NovoJFrame() {
        initComponents();
    }
    
    private void initComponents() {
        jButton1 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jButton1.setText("PESQUISA");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        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(149, 149, 149)
                .addComponent(jButton1)
                .addContainerGap(182, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(194, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(83, 83, 83))
        );
        pack();
    }


    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {  
	exemplo ex = new exemplo();
	ex.select();                                       
        
    }                                        
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NovoJFrame().setVisible(true);
            }
        });
    }
    
    
    
    private javax.swing.JButton jButton1;
    
}

Espero ter ajudado!

Criado 30 de maio de 2007
Ultima resposta 19 de jun. de 2007
Respostas 2
Participantes 3