Monday, November 11, 2013

Treinamento Java 2 Básico - Capítulo 5 JDBC


Capítulo 5 JDBC - sessão 7, 8, 9


Sessão 8:

Primeiramente devemos notar que estamos trabalhando na sessão 8 em que tive a oportunidade de aprender a montar uma GUI(graphical user interface) que permitirá inserir dados no Banco de dados Postgree(pode-se utilizar outro, desde que se tenha o driver de conexão). É necessário fazer o download do postgree. As configurações de CONEXÃO do BD estão definidas no pacote util que irei descrever melhor mais adiante para fixarmos o que aprendi. A GUI (graphical user interface) é a EntrevistadoGUI e para montar essa GUI devemos clicar com o botão direito do mouse em cima do pacote de visão e em novo Form Jframe (lembre-se de que em Swing uma janela de mais alto nível, que não está contida em nenhum outro componente, é chamada de JFrame. No AWT denomina-se quadro(Frame)). A GUI está na segunda figura abaixo:





Após definirmos nossa GUI devemos ter em mente que teremos que executar as queries que estão no pacote SQL. No caso da GUI acima iremos executar a query que está no arquivo pesquisa_dump no postgree.



Veja a query abaixo:

CREATE TABLE entrevistado (
  codigo SERIAL,
  nome varchar(30) NOT NULL,
  idade integer NOT NULL,
  fumante boolean NOT NULL,
  sexo char(1) NOT NULL,
  PRIMARY KEY (codigo)
) ;

-- Dumping data for table pesquisa.entrevistado: ~16 rows (approximately)

INSERT INTO entrevistado (nome, idade, fumante, sexo) VALUES
('MARIA', 18, 'false', 'F'),
('JOÃO', 41, 'true', 'M'),
('PEDRO', 32, 'false', 'M'),
('ANA', 30, 'false', 'F'),
('PAULO', 78, 'false', 'M'),
('REGINA', 70, 'true', 'F'),
('ROBERTO SOUZA', 65, 'true', 'M'),
('JULIANA', 42, 'false', 'F'),
('CARLA', 20, 'false', 'F'),
('APARECIDA', 52, 'false', 'F'),
('DANIEL', 25, 'false', 'M'),
('PROFESSOR', 51, 'true', 'M'),
('FABIO', 21, 'true', 'M'),
('IDOSO', 100, 'true', 'F'),
('GIOVANE DA SILVA', 22, 'false', 'M'),
('ELIAS RAMALHO', 35, 'true', 'M');

O BD está configurado da seguinte forma:


A estrutura de pastas do exercício EntrevistadoGUI é a que está abaixo:



O código referente a GUI EntrevistadoGUI.java possui diversas características como, por exemplo, os EVENTOS relacionados aos botões que mais adiante iremos tentar entender:

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  1. /*
  2.  * EntrevistadoGUI.java
  3.  *
  4.  * Created on 16/11/2010, 12:24:16
  5.  */

  6. package visao;

  7. import javax.swing.JOptionPane;
  8. import javax.swing.JSlider;
  9. import modelo.Entrevistado;
  10. import modelo.EntrevistadoDAO;

  11. /**
  12.  *
  13.  * @author Paulo Henrique Cayres
  14.  */
  15. public class EntrevistadoGUI extends javax.swing.JFrame {

  16.     /** Creates new form EntrevistadoGUI */
  17.     public EntrevistadoGUI() {
  18.         initComponents();
  19.     }

  20.     /** This method is called from within the constructor to
  21.      * initialize the form.
  22.      * WARNING: Do NOT modify this code. The content of this method is
  23.      * always regenerated by the Form Editor.
  24.      */
  25.     @SuppressWarnings("unchecked")
  26.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  27.     private void initComponents() {..}


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

  31.     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                       

  32.   //Nesse trecho notamos que no EVENTO clique do botão INSERIR estamos fazendo uma validação para verificar se o campo nome da GUI entrevistadoGUI.java está preenchido. 

  33.        if( jTextField1.getText().isEmpty() ){
  34.            JOptionPane.showMessageDialog(null,"Nome do entrevistado é obrigatório", "AVISO", JOptionPane.WARNING_MESSAGE);
  35.            jTextField1.requestFocus() ;
  36.            return ;
  37.        }
  38.        // 1) Criação do objeto 'modelo' Entrevistado
  39.        // e setar atributos com conteúdo dos componentes gráficos
  40.        Entrevistado ent = new Entrevistado() ;

  41.        ent.setNome( jTextField1.getText().toUpperCase() );
  42.        ent.setIdade( (byte) jSlider1.getValue() );

  43.        if( jRadioButton1.isSelected() )
  44.             ent.setFumante(false);
  45.        else
  46.             ent.setFumante(true);

  47.        if( jRadioButton3.isSelected() )
  48.             ent.setSexo('F');
  49.        else
  50.             ent.setSexo('M');

  51.        // 2) Criação do objeto 'DAO' que fará a conexão com o BD

  52.        EntrevistadoDAO entDAO = new EntrevistadoDAO() ;

  53.        if( entDAO.insere(ent) )
  54.             limpar() ;   //Veja a linha 84
  55.     }          

  56.                               
  57. //Código associado ao EVENTO do botão fechar
  58.     private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  59.         System.exit(0);
  60.     }

  61. // O código abaixo é referente ao EVENTO clique do botão limpar.                                        

  62.     private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                               
  63.         limpar() ;
  64.     }                                              
  65.     private void limpar(){
  66.         jTextField1.setText("");
  67.         jSlider1.setValue(25);
  68.         jLabel5.setText(String.valueOf(25));
  69.         jRadioButton1.setSelected(true);
  70.         jRadioButton3.setSelected(true);
  71.     }


  72. //Código associado ao EVENTO do botão deslizante
  73.     private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {                                      
  74.         // TODO add your handling code here:
  75.         JSlider temp = (JSlider) evt.getSource() ;
  76.         if( !temp.getValueIsAdjusting() )
  77.             jLabel5.setText(String.valueOf(temp.getValue()));

  78.     }                               

  79. // O código abaixo está associado ao botão Listar TextArea  

  80.     private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  81.        // botão LISTAR em uma TextArea
  82.        ListarTextAreaGUI fListar = new ListarTextAreaGUI() ;
  83.        fListar.setVisible(true);
  84.        
  85.        // Lista no modo texto
  86.        /* 
  87.        EntrevistadoDAO entDAO = new EntrevistadoDAO() ;

  88.        String nome[] = entDAO.lista() ;

  89.        for( int i = 0 ; i < nome.length ; i++ )
  90.            System.out.println( "Nome: " + nome[i]) ;
  91.        */
  92.     } 
  93.                                        
  94. //Código associado ao EVENTO do botão Listar JTable
  95.     private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  96.       // botão LISTAR em JTable
  97.        ListarJTableGUI fListarJT = new ListarJTableGUI() ;
  98.        fListarJT.setVisible(true);
  99.     
  100.     }                                        

  101.     /**
  102.     * @param args the command line arguments
  103.     */
  104.     public static void main(String args[]) {
  105.         java.awt.EventQueue.invokeLater(new Runnable() {
  106.             public void run() {
  107.                 new EntrevistadoGUI().setVisible(true);
  108.             }
  109.         });
  110.     }

  111.     // Variables declaration - do not modify                     
  112.     private javax.swing.ButtonGroup buttonGroup1;
  113.     private javax.swing.ButtonGroup buttonGroup2;
  114.     private javax.swing.JButton jButton1;
  115.     private javax.swing.JButton jButton2;
  116.     private javax.swing.JButton jButton3;
  117.     private javax.swing.JButton jButton4;
  118.     private javax.swing.JLabel jLabel1;
  119.     private javax.swing.JLabel jLabel2;
  120.     private javax.swing.JLabel jLabel3;
  121.     private javax.swing.JLabel jLabel4;
  122.     private javax.swing.JLabel jLabel5;
  123.     private javax.swing.JRadioButton jRadioButton1;
  124.     private javax.swing.JRadioButton jRadioButton2;
  125.     private javax.swing.JRadioButton jRadioButton3;
  126.     private javax.swing.JRadioButton jRadioButton4;
  127.     private javax.swing.JSlider jSlider1;
  128.     private javax.swing.JTextField jTextField1;
  129.     private javax.swing.JToggleButton jToggleButton1;
  130.     // End of variables declaration                   

  131. }
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


Linha 50 do código da GUI EntrevistadoGUI.java:

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */

  5. package modelo;

  6. /*
  7.  *
  8.  * @author Paulo Henrique Cayres
  9.  */
  10. public class Entrevistado {

  11.     private Long codigo;
  12.     private String nome;
  13.     private byte idade;
  14.     private boolean fumante;
  15.     private char sexo;

  16.     public Entrevistado() {
  17.     }

  18.     public boolean isFumante() {
  19.         return fumante;
  20.     }

  21.     public void setFumante(boolean fumante) {
  22.         this.fumante = fumante;
  23.     }

  24.     public byte getIdade() {
  25.         return idade;
  26.     }

  27.     public void setIdade(byte idade) {
  28.         this.idade = idade;
  29.     }

  30.     public String getNome() {
  31.         return nome;
  32.     }

  33.     public void setNome(String nome) {
  34.         this.nome = nome;
  35.     }

  36.     public char getSexo() {
  37.         return sexo;
  38.     }

  39.     public void setSexo(char sexo) {
  40.         this.sexo = sexo;
  41.     }

  42. }



Linha 67 (classe EntrevistadoDAO) do código da GUI EntrevistadoGUI.java:

  1. package modelo;

  2. import controle.ConnectionFactoryComProperties;
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.ResultSetMetaData;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. import java.util.ArrayList;
  10. import javax.swing.JOptionPane;

  11. /**
  12.  *
  13.  * @author Paulo Henrique Cayres
  14.  */
  15. public class EntrevistadoDAO {
  16.     // atributo para conexão com o BD
  17.     private Connection con;

  18.     // construtor do DAO estabelece a conexão com o BD
  19.     public EntrevistadoDAO() {
  20.       this.con = new ConnectionFactoryComProperties().getConnection();
  21.     }

  22.     // métodos implementados aqui são as operações CRUD desejadas

  23.     public boolean insere(Entrevistado entrevistado) {
  24.         String sql = "INSERT INTO entrevistado " +
  25.                      "(nome, idade, fumante, sexo) VALUES (?,?,?,?)";

  26.         try {
  27.             // utilização de SQL preparadada
  28.             PreparedStatement stmt = con.prepareStatement(sql);
  29.             // ajuste dos parâmetros (?), com o método 'get' apropriado
  30.             stmt.setString(1, entrevistado.getNome());
  31.             stmt.setInt(2, entrevistado.getIdade());
  32.             stmt.setBoolean(3, entrevistado.isFumante());
  33.             stmt.setString( 4, String.valueOf( entrevistado.getSexo()) );
  34.             // execução da consulta
  35.             stmt.executeUpdate();
  36.             // encerramento do uso do canal
  37.             stmt.close();

  38.             JOptionPane.showMessageDialog(null,"Registro inserido com sucesso!","INFORMAÇÃO", JOptionPane.INFORMATION_MESSAGE);
  39.             return true ;
  40.         } catch (SQLException e) {
  41.             throw new RuntimeException(e);
  42.         }
  43.     }

  44.     public String [] lista() {

  45.         String sql = "SELECT * FROM entrevistado ORDER BY nome" ;
  46. //        String [] dados = null ; // definição da estrutura de dados de retorno
  47.         ArrayList<String> dados = new ArrayList<>() ; // definição da estrutura de dados de retorno
  48.         try {
  49.             Statement stmt = this.con.createStatement() ;

  50.             ResultSet rs = stmt.executeQuery(sql);
  51.             ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData() ;
  52.             

  53.             // percorrer o ResultSet para compor a estrutura de dados de retorno
  54.             int idxLinha = 0;
  55.             while(rs.next()) {
  56.                 dados.add(rs.getString("nome"));
  57.                 // e outros dados que julgar necessário
  58.                 idxLinha++;
  59.             }
  60.             stmt.close();
  61.         } catch (SQLException e) {
  62.             throw new RuntimeException(e);
  63.         }
  64.         
  65.         String []retorno = new String[dados.size()];
  66.         int i=0;
  67.         for(String temp:dados)
  68.             retorno[i++] = temp;

  69.         return retorno;
  70.     }


  71.     // Utilização de JTable via JDBC
  72.     public ArrayList<Object[]> listaAll( String sql ) {
  73.         
  74.         ArrayList<Object[]> dados = new ArrayList<>() ; // definição da estrutura de dados de retorno
  75.         try {
  76.             PreparedStatement stmt = this.con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE ) ;

  77.             ResultSet rs = stmt.executeQuery();
  78.            
  79.             ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData() ;
  80.             
  81.             int nCols = rsmd.getColumnCount() ;
  82.             
  83.             String colunas[] = new String[nCols] ;
  84.             for( int i = 0 ; i < nCols ; i++ ){
  85.                 colunas[i] = rsmd.getColumnName(i+1);
  86.             }
  87.                         
  88.             dados.clear() ;
  89.             dados.add(colunas); // guardando a descrição dos campos em primeiro
  90.             
  91.             while( rs.next()){
  92.                 Object l[] = new Object[nCols] ;
  93.                 for( int i = 0 ; i < nCols; i++){
  94.                     l[i] = rs.getObject(i+1) ;
  95.                 }
  96.                 dados.add(l);
  97.             }
  98.             
  99.             rs.close() ;
  100.             stmt.close();
  101.             
  102.         } catch (SQLException e) {
  103.             throw new RuntimeException(e);
  104.         }

  105.         return dados;

  106.     }

  107. }



Linha 23 da linha 67 (Classe ConnectionFactoryComProperties) do código da GUI EntrevistadoGUI.java:

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package controle;

  6. import java.io.IOException;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.SQLException;
  10. import java.util.Properties;

  11. /**
  12.  *
  13.  * @author Paulo Henrique Cayres
  14.  */
  15. public class ConnectionFactoryComProperties{
  16.     
  17.     public Connection getConnection() {
  18.         try {
  19.             // Criação de um objeto de propriedades
  20.             Properties prop = new Properties();

  21.             // leitura/carga do arquivo texto com as propriedades
  22.             prop.load( getClass().getResourceAsStream("../util/bancoDeDados.properties"));

  23.             // obtenção do valor de cada parâmetro através do método getProperty
  24.             String dbDriver = prop.getProperty("db.driver");
  25.             String dbUrl = prop.getProperty("db.url");
  26.             String dbUser = prop.getProperty("db.user");
  27.             String dbPwd = prop.getProperty("db.pwd");

  28.  

  29.             Class.forName(dbDriver);
  30.             return DriverManager.getConnection(dbUrl, dbUser, dbPwd);

  31.         } catch (ClassNotFoundException | IOException | SQLException ex) {
  32.             throw new RuntimeException(ex);
  33.         }
  34.     }
  35. }



Linha 25 da linha 23 da linha 67 (BancoDeDados.properties) do código da GUI EntrevistadoGUI.java:

  1. db.driver=org.postgresql.Driver
  2. db.url=jdbc:postgresql://localhost:5432/postgres
  3. db.user=postgres
  4. db.pwd=rnpesr


Linhas 101 a 117 do código da GUI EntrevistadoGUI.java:



  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */

  5. /*
  6.  * ListarTextAreaGUI.java
  7.  *
  8.  * Created on 24/09/2012, 13:54:39
  9.  */
  10. package visao;

  11. import modelo.EntrevistadoDAO;

  12. /**
  13.  *
  14.  * @author Paulo Henrique Cayres
  15.  */
  16. public class ListarTextAreaGUI extends javax.swing.JFrame {

  17.     /** Creates new form ListarTextAreaGUI */
  18.     public ListarTextAreaGUI() {
  19.         initComponents();
  20.         
  21.         setTitle( "Relação de Entrevistados") ;
  22.         
  23.         EntrevistadoDAO entDAO = new EntrevistadoDAO() ;

  24.         String nome[] = entDAO.lista() ;

  25.         for( int i = 0 ; i < nome.length ; i++ ){
  26.            jTextArea1.append( (i+1) + " " + nome[i] +"\n") ;
  27.            //TESTE para verificar resultado da consulta => System.out.println( "Nome: " + nome[i]) ;
  28.         }
  29.     }

  30.     /** This method is called from within the constructor to
  31.      * initialize the form.
  32.      * WARNING: Do NOT modify this code. The content of this method is
  33.      * always regenerated by the Form Editor.
  34.      */
  35.     @SuppressWarnings("unchecked")
  36.    

  37.     /**
  38.      * @param args the command line arguments
  39.      */
  40.     public static void main(String args[]) {
  41.         /* Set the Nimbus look and feel */
  42.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  43.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  44.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
  45.          */
  46.      

  47.         /* Create and display the form */
  48.         java.awt.EventQueue.invokeLater(new Runnable() {

  49.             public void run() {
  50.                 new ListarTextAreaGUI().setVisible(true);
  51.             }
  52.         });
  53.     }
  54.     // Variables declaration - do not modify                     
  55.     private javax.swing.JScrollPane jScrollPane1;
  56.     private javax.swing.JTextArea jTextArea1;
  57.     // End of variables declaration                   
  58. }



Linhas 120 a 125 do código da GUI EntrevistadoGUI.java:



  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */

  5. /*
  6.  * ListarJTableGUI.java
  7.  *
  8.  * Created on 24/09/2012, 14:27:28
  9.  */
  10. package visao;

  11. import controle.QueryTableModel;
  12. import javax.swing.JTable;

  13. /**
  14.  *
  15.  * @author Paulo Henrique Cayres
  16.  */
  17. public class ListarJTableGUI extends javax.swing.JFrame {

  18.     /** Creates new form ListarJTableGUI */
  19.     public ListarJTableGUI() {
  20.         initComponents();
  21.         
  22.        // constrói o componente "tabela", com os parâmetros: colunas (título) e dados (do cursor)
  23.        // tabela = new JTable( new QueryTableModel("SELECT * FROM entrevistado ORDER BY nome;") ) ; 
  24.        QueryTableModel qtm = new QueryTableModel("SELECT * FROM entrevistado ORDER BY nome;") ; 
  25.        tabela = new JTable( qtm ) ;
  26.        
  27.        jScrollPane1.setViewportView(tabela); // scrollpane já criado no initComp.. então atualizar com tabela
  28.        
  29.        setTitle("Exemplo de JTable com JDBC") ;
  30.        getContentPane().add( jScrollPane1 , "Center") ;
  31.        setDefaultCloseOperation( DISPOSE_ON_CLOSE );
  32.     }

  33.     /** This method is called from within the constructor to
  34.      * initialize the form.
  35.      * WARNING: Do NOT modify this code. The content of this method is
  36.      * always regenerated by the Form Editor.
  37.      */
  38.     @SuppressWarnings("unchecked")
  39.    
  40.     /**
  41.      * @param args the command line arguments
  42.      */
  43.     public static void main(String args[]) {
  44.         /* Set the Nimbus look and feel */
  45.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  46.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  47.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
  48.          */
  49.     

  50.         /* Create and display the form */
  51.         java.awt.EventQueue.invokeLater(new Runnable() {

  52.             public void run() {
  53.                 new ListarJTableGUI().setVisible(true);
  54.             }
  55.         });
  56.     }
  57.     // Variables declaration - do not modify                     
  58.     private javax.swing.JScrollPane jScrollPane1;
  59.     // End of variables declaration                   
  60.     private JTable tabela ;
  61. }

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


EntrevistadoGUI:


---------------------------------------------------------------------------------------------------------

Sessão 9:

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import java.sql.CallableStatement;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.SQLException;
  10. import java.sql.Types;

  11. /**
  12.  *
  13.  * @author Paulo Henrique Cayres
  14.  */
  15. public class ExemploCallableStatement {
  16.     
  17.     public static void main(String[] args) {
  18.         
  19.         try {
  20.             Class.forName("org.postgresql.Driver") ;
  21.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "rnpesr");
  22.             
  23.             // Chamada da function
  24.             CallableStatement st = connect.prepareCall("{? = CALL consultaaluno(?)}");
  25.             st.registerOutParameter(1, Types.VARCHAR);
  26.             st.setInt(2, 2);
  27.             st.execute();
  28.             
  29.            
  30.             if(st.getString(1) == null)
  31.                 System.out.println("Código inválido!!!");
  32.             else
  33.                 System.out.println(st.getString(1));
  34.                 
  35.                 

  36.         } 
  37.         catch (SQLException | ClassNotFoundException ex) {
  38.             System.out.println(ex.toString());
  39.         }

  40.     }
  41.     
  42. }



A tela abaixo mostra a função (no postgree uma procedure é a mesma coisa que function):


Na tela abaixo temos a tabela aluno que servirá para consultar o aluno:



As telas abaixo mostram 2 execuções do programa, uma execução com um parâmetro correto e a outra com um parâmetro inválido que não existe na tabela aluno:





xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


Um outro exemplo bem parecido com o exercicio ExemploCallableStatement  acima é o ExemploConsultaAluno:


  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import java.sql.CallableStatement;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.SQLException;
  10. import java.sql.Types;

  11. /**
  12.  *
  13.  * @author Aluno
  14.  */
  15. public class ExemploConsultaAluno {

  16.     public static void main(String[] args) {
  17.         try {
  18.             Class.forName("org.postgresql.Driver");
  19.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "rnpesr");

  20.             // Chamada da function
  21.             CallableStatement st = connect.prepareCall("{? = CALL consultaaluno(?)}");
  22.             st.registerOutParameter(1, Types.VARCHAR);
  23.             st.setInt(2, 2);
  24.             st.execute();

  25.             javax.swing.JOptionPane.showMessageDialog(null, st.getString(1));

  26.         } catch (SQLException | ClassNotFoundException ex) {
  27.             System.out.println(ex.toString());
  28.         }

  29.     }
  30. }


Se o parâmetro da linha 27 fosse st.setInt(2,1) o resulta seria Paulo Cayres. No entanto, teremos o resultado abaixo:




xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import java.sql.Connection;
  7. import java.sql.DriverManager;
  8. import java.sql.SQLException;
  9. import java.sql.Statement;

  10. /**
  11.  *
  12.  * @author Paulo Henrique Cayres
  13.  */
  14. public class ExemploBatch {
  15.     
  16.     public static void main(String[] args) {

  17.         try {
  18.             Class.forName("org.postgresql.Driver") ;
  19.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
  20.             
  21.             connect.setAutoCommit(false);
  22.             
  23.             try{
  24.                 Statement st = connect.createStatement()
  25.                 st.addBatch("insert into empregado(ssn, pnome, unome, sexo, dno) values('123','Paulo','Paulo','M', '1')");
  26.                 st.addBatch("insert into empregado(ssn, pnome, unome, sexo, dno) values('456','Henrique','Cayres','M', '1')");
  27.                 st.addBatch("inserte into empregado(ssn, pnome, unome, sexo, dno) values('789','Cayres','Henrique','M', '1')");
  28.                 
  29.                 st.executeBatch();
  30.                 connect.commit();
  31.             }
  32.             catch(SQLException e){
  33.                 System.out.println("Erro ao tentar incluir registros!!!\n\n"+e.toString());
  34.                 try{
  35.                     connect.rollback();
  36.                 }
  37.                 catch(SQLException ex){
  38.                     System.out.println("Erro ao tentar executar rollback!!!\n\n"+ex.toString());
  39.                 }
  40.             }
  41.             finally{
  42.                 try{
  43.                     connect.commit();
  44.                     connect.setAutoCommit(true);
  45.                     connect.close();
  46.                 }
  47.                 catch(SQLException ex){
  48.                     System.out.println("Erro ao tentar executar commit!!!\n\n"+ex.toString());
  49.                 }
  50.             }
  51.             
  52.             
  53.         } 
  54.         catch (SQLException | ClassNotFoundException ex) {
  55.             System.out.println("Erro de conexão com o banco de dados!!!\n\n"+ex.toString());
  56.         }
  57.         
  58.     }
  59.     
  60. }
O código acima irá gerar um erro ao ser executado por causa da linha 30 veja:


Se executarmos o código e deixarmos corretamente a linha 30 irá executar o método batch corretamente da linha 32.



xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import java.sql.Connection;
  7. import java.sql.DriverManager;
  8. import java.sql.SQLException;
  9. import java.sql.Statement;

  10. /**
  11.  *
  12.  * @author Paulo Henrique Cayres
  13.  */
  14. public class ExemploCommit {
  15.     
  16.     public static void main(String[] args) {

  17.         try {
  18.             Class.forName("org.postgresql.Driver") ;
  19.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
  20.             
  21.             connect.setAutoCommit(false);
  22.             
  23.             try{
  24.                 Statement st = connect.createStatement();
  25.                 st.execute("insert into empregado(ssn, pnome, unome, sexo, dno) values('123','Paulo','Paulo','M', '1')");
  26.                 st.execute("insert into empregado(ssn, pnome, unome, sexo, dno) values('456','Cayres','Cayres','M', '1')");
  27.                 st.execute("insertw into empregado(ssn, pnome, unome, sexo, dno) values('789','Erro','Erro','M', '1')");
  28.             }
  29.             catch(SQLException e){
  30.                 System.out.println("Erro ao tentar incluir registros!!!\n\n"+e.toString());
  31.                 try{
  32.                     connect.rollback();
  33.                 }
  34.                 catch(SQLException ex){
  35.                     System.out.println("Erro ao tentar executar rollback!!!\n\n"+ex.toString());
  36.                 }
  37.             }
  38.             finally{
  39.                 try{
  40.                     connect.commit();
  41.                     connect.close();
  42.                 }
  43.                 catch(SQLException ex){
  44.                     System.out.println("Erro ao tentar executar commit!!!\n\n"+ex.toString());
  45.                 }
  46.             }
  47.             
  48.             
  49.         } 
  50.         catch (SQLException | ClassNotFoundException ex) {
  51.             System.out.println("Erro de conexção com o banco de dados!!!\n\n"+ex.toString());
  52.         }
  53.         
  54.     }
  55.     
  56. }




A diferença dessa classe ExemploCommit para a classe ExemploBatch é que nessa não existe a cláusula st.executeBatch().
O resultado do código acima será:




Se consertarmos o insert da linha 30 irá executar corretamente e irá inserir na tabela os 3 registros.

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import coreservlets.DBResults;
  7. import coreservlets.DatabaseUtilities;
  8. import java.sql.Connection;
  9. import java.sql.DriverManager;
  10. import java.sql.SQLException;

  11. /**
  12.  *
  13.  * @author Paulo Henrique Cayres
  14.  */
  15. public class ExemploDatabaseUtilities {
  16.     
  17.     public static void main(String[] args) {
  18.         
  19.         try {
  20.             Class.forName("org.postgresql.Driver") ;
  21.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");

  22.             //uso de DBResults
  23.             DBResults teste = DatabaseUtilities.getQueryResults(connect, "select * from empregado", false) ;
  24.             System.out.println(teste.toHTMLTable(null));
  25.             
  26.             //uso de DatabaseUtilities
  27.             DatabaseUtilities.printTable(connect, "empregado", 40, true);
  28.             DatabaseUtilities.printTableData("empregado", teste, 40, true);
  29.             
  30.             
  31.         } 
  32.         catch (SQLException | ClassNotFoundException ex) {
  33.             System.out.println("Erro de conexção com o banco de dados!!!\n\n"+ex.toString());
  34.         }
  35.         
  36.         
  37.     }
  38.     
  39. }

O resultado do código acima será mais ou menos o que está nas telas abaixo:





xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import java.sql.CallableStatement;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.SQLException;
  10. import java.sql.Types;

  11. /**
  12.  *
  13.  * @author paulo983
  14.  */
  15. public class ExemploIsValidUser {

  16.         
  17.     public static void main(String[] args) {
  18.         
  19.         try {
  20.             Class.forName("org.postgresql.Driver") ;
  21.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
  22.             
  23.             // Chamada da function
  24.             CallableStatement st = connect.prepareCall("{? = CALL isvaliduser(?,?)}");
  25.             st.registerOutParameter(1, Types.BOOLEAN);
  26.             st.setString(2, "cayres");
  27.             st.setString(3, "1234");
  28.             st.execute();
  29.             
  30.            
  31.             if(st.getBoolean(1))
  32.                 System.out.println("Acesso Liberado!");
  33.             else
  34.                 System.out.println("Acesso Negado!");
  35.                 
  36.         } 
  37.         catch (SQLException | ClassNotFoundException ex) {
  38.             System.out.println(ex.toString());
  39.         }

  40.     }

  41. }
Repare que na linha 27 temos 3 interrogações que nessa ordem serão usadas nas linhas 28, 29, 30. Como resultado teremos:


Caso o parâmetro da linha 30 seja incorreto, ou seja, a senha que será passada como parâmetro esteja incorreta. Por exemplo, se a linha 30 estivesse dessa forma st.setString(3, "123") tereíamos o seguinte resultado:




xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import java.sql.Connection;
  7. import java.sql.DatabaseMetaData;
  8. import java.sql.DriverManager;
  9. import java.sql.SQLException;

  10. /**
  11.  *
  12.  * @author Paulo Henrique Cayres
  13.  */
  14. public class ExemploMetaData {
  15.     
  16.     public static void main(String[] args){
  17.         try {
  18.             Class.forName("org.postgresql.Driver") ;
  19.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432", "postgres", "rnpesr");
  20.             
  21.             //procurar informações sobre o banco de dados como um todo
  22.             DatabaseMetaData dbMetaData = connect.getMetaData();
  23.             
  24.             System.out.println("Banco de Dados: "+ dbMetaData.getDatabaseProductName());
  25.             System.out.println("Versão do Banco de Dados: "+ dbMetaData.getDatabaseProductVersion());
  26.             
  27.         } 
  28.         catch (SQLException | ClassNotFoundException ex) {}

  29.         
  30.     }
  31.     
  32. }

Teremos como resultado o seguinte:


xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import java.sql.Connection;
  7. import java.sql.DriverManager;
  8. import java.sql.ResultSet;
  9. import java.sql.ResultSetMetaData;
  10. import java.sql.SQLException;
  11. import java.sql.Statement;

  12. /**
  13.  *
  14.  * @author paulo983
  15.  */
  16. public class ExemploMetaDataTabela {
  17.     
  18.     public static void main(String[] args) {
  19.         
  20.         try {
  21.             Class.forName("org.postgresql.Driver") ;
  22.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
  23.             
  24.             //SQL que retorna todos os empregados em ordem alfabética
  25.             Statement st = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
  26.             
  27.             String query  = "select * from aluno order by nome";
  28.             ResultSet rs = st.executeQuery(query);

  29.             ResultSetMetaData rsMetaData = rs.getMetaData();

  30.             
  31.             // abtendo informações sobre o result set
  32.             for(int i=1; i <= rsMetaData.getColumnCount(); i++){
  33.                 
  34.                 System.out.println(rsMetaData.getColumnName(i) + " - " + 
  35.                                     rsMetaData.getColumnTypeName(i) + " - " + 
  36.                                     rsMetaData.getPrecision(i) + " - " + 
  37.                                     rsMetaData.getColumnDisplaySize(i) + " - " + 
  38.                                     rsMetaData.isCaseSensitive(i) + " - " + 
  39.                                     rsMetaData.isCurrency(i) + " - " + 
  40.                                     rsMetaData.isDefinitelyWritable(i) + " - " + 
  41.                                     rsMetaData.isNullable(i) + " - " + 
  42.                                     rsMetaData.isReadOnly(i) + " - " + 
  43.                                     rsMetaData.isSearchable(i) + " - " + 
  44.                                     rsMetaData.isWritable(i) + " - " + 
  45.                                     rsMetaData.isAutoIncrement(i));
  46.                 
  47.             }

  48.             // percorrendo o result set
  49.             System.out.println("--------------------------");
  50.             rs.beforeFirst();
  51.             while(rs.next()){
  52.                 System.out.println(rs.getString("nome"));
  53.             }
  54.            
  55.         } 
  56.         catch (SQLException | ClassNotFoundException ex) {
  57.             System.out.println(ex.toString());
  58.         }
  59.          
  60.     }
  61.     
  62. }

Segue o resultado da execução do código acima:



xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import java.sql.CallableStatement;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.SQLException;
  10. import java.sql.Types;

  11. /**
  12.  *
  13.  * @author paulo983
  14.  */
  15. public class ExemploStoredProcedure {
  16.   
  17.         
  18.     public static void main(String[] args) {
  19.         
  20.         try {
  21.             Class.forName("org.postgresql.Driver") ;
  22.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
  23.             
  24.             // Chamada da function
  25.             CallableStatement st = connect.prepareCall("{? = CALL maiuscula(?)}");
  26.             st.registerOutParameter(1, Types.VARCHAR);
  27.             st.setString(2, "Renato Bueno");
  28.             st.execute();
  29.                         
  30.             System.out.println(st.getString(1));
  31.             
  32.         } 
  33.         catch (SQLException | ClassNotFoundException ex) {
  34.             System.out.println(ex.toString());
  35.         }

  36.     }
  37.     
  38. }
Teremos como resultado o seguinte:



O código abaixo se refere a procedure ( no postgree procedure é sinônimo de function):



xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import java.sql.CallableStatement;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.SQLException;
  10. import java.sql.Types;
  11. import javax.swing.JOptionPane;

  12. /**
  13.  *
  14.  * @author Aluno
  15.  */
  16. public class exercicioValidaUser extends javax.swing.JFrame {

  17.     /**
  18.      * Creates new form exercicioValidaUser
  19.      */
  20.     public exercicioValidaUser() {
  21.         initComponents();
  22.     }

  23.     /**
  24.      * This method is called from within the constructor to initialize the form.
  25.      * WARNING: Do NOT modify this code. The content of this method is always
  26.      * regenerated by the Form Editor.
  27.      */
  28.     @SuppressWarnings("unchecked")
  29.   

  30.     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  31.         // TODO add your handling code here:
  32.         try {
  33.             Class.forName("org.postgresql.Driver");
  34.             Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "rnpesr");

  35.             // Chamada da function
  36.             CallableStatement st = connect.prepareCall("{? = CALL isvaliduser(?,?)}");
  37.             st.registerOutParameter(1, Types.BOOLEAN);            
  38.             st.setString(2, jTextField1.getText());
  39.             String pass = new String(jPasswordField1.getPassword());
  40.             st.setString(3, pass);
  41.             st.execute();


  42.             if (pass.equals("1234")) {
  43.                 javax.swing.JOptionPane.showMessageDialog(null, "Acesso liberado", "Logon", JOptionPane.WARNING_MESSAGE);
  44.             } else {
  45.                 javax.swing.JOptionPane.showMessageDialog(null, "Acesso negado", "Logon", JOptionPane.OK_OPTION);
  46.             }

  47.         } catch (SQLException | ClassNotFoundException ex) {
  48.             System.out.println(ex.toString());
  49.         }
  50.     }                                        

  51.     /**
  52.      * @param args the command line arguments
  53.      */
  54.     public static void main(String args[]) {
  55.        

  56.         /* Create and display the form */
  57.         java.awt.EventQueue.invokeLater(new Runnable() {
  58.             public void run() {
  59.                 new exercicioValidaUser().setVisible(true);
  60.             }
  61.         });
  62.     }
  63.     // Variables declaration - do not modify                     
  64.     private javax.swing.JButton jButton1;
  65.     private javax.swing.JLabel jLabel1;
  66.     private javax.swing.JLabel jLabel2;
  67.     private javax.swing.JPasswordField jPasswordField1;
  68.     private javax.swing.JTextField jTextField1;
  69.     // End of variables declaration                   
  70. }

Nesse exercício a validação irá funcionar apenas se a senha estiver correta independente do usuário digitado.(meio sem nexo, mas é apenas pra exemplificar. Logo abaixo teremos um código com validação completa):


Se a senha estiver incorreta o resultado será o que a tela abaixo está mostrando:



xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package visao;

  6. import controle.AlunoDAO;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9. import modelo.Aluno;

  10. /**
  11.  *
  12.  * @author paulo983
  13.  */
  14. public class ExemploLoginAluno extends javax.swing.JFrame {

  15.     /**
  16.      * Creates new form ExemploLoginAluno
  17.      */
  18.     public ExemploLoginAluno() {
  19.         initComponents();
  20.     }

  21.     /**
  22.      * This method is called from within the constructor to initialize the form.
  23.      * WARNING: Do NOT modify this code. The content of this method is always
  24.      * regenerated by the Form Editor.
  25.      */
  26.     @SuppressWarnings("unchecked")
  27.                         

  28.     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  29.         // TODO add your handling code here:
  30.         Aluno a = new Aluno(jTextField1.getText(),
  31.                             new String(jPasswordField1.getPassword()));
  32.         AlunoDAO teste;
  33.         try {
  34.             teste = new AlunoDAO();
  35.             if(teste.isValidUser(a))
  36.                 javax.swing.JOptionPane.showMessageDialog(null, "Acesso Liberado!");
  37.             else
  38.                 javax.swing.JOptionPane.showMessageDialog(null, "Acesso Negado!");
  39.         } catch (Exception ex) {
  40.             Logger.getLogger(ExemploLoginAluno.class.getName()).log(Level.SEVERE, null, ex);
  41.         }
  42.     }                                        

  43.     /**
  44.      * @param args the command line arguments
  45.      */
  46.     public static void main(String args[]) {
  47.         
  48.        /* Create and display the form */
  49.         java.awt.EventQueue.invokeLater(new Runnable() {
  50.             public void run() {
  51.                 new ExemploLoginAluno().setVisible(true);
  52.             }
  53.         });
  54.     }
  55.     // Variables declaration - do not modify                     
  56.     private javax.swing.JButton jButton1;
  57.     private javax.swing.JButton jButton2;
  58.     private javax.swing.JLabel jLabel1;
  59.     private javax.swing.JLabel jLabel2;
  60.     private javax.swing.JPasswordField jPasswordField1;
  61.     private javax.swing.JTextField jTextField1;
  62.     // End of variables declaration                   
  63. }
Caso o usuário e a senha estejam corretos teremos o resultado abaixo:


Caso a senha ou o usuário estejam incorretos:




Os códigos das linhas 35 e 39 são, respectivamente:

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package modelo;

  6. /**
  7.  *
  8.  * @author Paulo Henrique Cayres
  9.  */
  10. public class Aluno {
  11.     
  12.     private int idAluno;
  13.     private String nome;
  14.     private String usuario;
  15.     private String senha;

  16.     public Aluno() {
  17.     }

  18.     public Aluno(String usuario, String senha) {
  19.         this.usuario = usuario;
  20.         this.senha = senha;
  21.     }

  22.     public Aluno(int idAluno, String nome, String usuario, String senha) {
  23.         this.idAluno = idAluno;
  24.         this.nome = nome;
  25.         this.usuario = usuario;
  26.         this.senha = senha;
  27.     }

  28.     public int getIdAluno() {
  29.         return idAluno;
  30.     }

  31.     public void setIdAluno(int idAluno) {
  32.         this.idAluno = idAluno;
  33.     }

  34.     public String getNome() {
  35.         return nome;
  36.     }

  37.     public void setNome(String nome) {
  38.         this.nome = nome;
  39.     }

  40.     public String getUsuario() {
  41.         return usuario;
  42.     }

  43.     public void setUsuario(String usuario) {
  44.         this.usuario = usuario;
  45.     }

  46.     public String getSenha() {
  47.         return senha;
  48.     }

  49.     public void setSenha(String senha) {
  50.         this.senha = senha;
  51.     }
  52.    
  53. }
----------------------------------------------------------------
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package controle;

  6. import java.sql.CallableStatement;
  7. import java.sql.Connection;
  8. import java.sql.SQLException;
  9. import java.sql.Types;
  10. import modelo.Aluno;

  11. /**
  12.  *
  13.  * @author Paulo Henrique Cayres
  14.  */
  15. public class AlunoDAO {

  16.     private Connection con;

  17.     public AlunoDAO() throws Exception {
  18.       this.con = new ConnectionFactoryComProperties().getConnection();
  19.     }
  20.     
  21.     public boolean isValidUser(Aluno a ){

  22.         try {
  23.              CallableStatement  st = con.prepareCall("{? = CALL isvaliduser(?,?)}");
  24.             // Chamada da function
  25.             st.registerOutParameter(1, Types.BOOLEAN);
  26.             st.setString(2, a.getUsuario());
  27.             st.setString(3, a.getSenha());
  28.             st.execute();

  29.             return st.getBoolean(1);                
  30.         } 
  31.         catch (SQLException ex) {
  32.             System.out.println(ex.toString());
  33.             return false;
  34.         }        
  35.     }                              

  36. }

A função isvaliduser da linha 28 é a seguinte:



No comments:

Post a Comment