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');
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
- /*
- * EntrevistadoGUI.java
- *
- * Created on 16/11/2010, 12:24:16
- */
- package visao;
- import javax.swing.JOptionPane;
- import javax.swing.JSlider;
- import modelo.Entrevistado;
- import modelo.EntrevistadoDAO;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class EntrevistadoGUI extends javax.swing.JFrame {
- /** Creates new form EntrevistadoGUI */
- public EntrevistadoGUI() {
- 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() {..}
- private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- }
- private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
- //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.
- if( jTextField1.getText().isEmpty() ){
- JOptionPane.showMessageDialog(null,"Nome do entrevistado é obrigatório", "AVISO", JOptionPane.WARNING_MESSAGE);
- jTextField1.requestFocus() ;
- return ;
- }
- // 1) Criação do objeto 'modelo' Entrevistado
- // e setar atributos com conteúdo dos componentes gráficos
- Entrevistado ent = new Entrevistado() ;
- ent.setNome( jTextField1.getText().toUpperCase() );
- ent.setIdade( (byte) jSlider1.getValue() );
- if( jRadioButton1.isSelected() )
- ent.setFumante(false);
- else
- ent.setFumante(true);
- if( jRadioButton3.isSelected() )
- ent.setSexo('F');
- else
- ent.setSexo('M');
- // 2) Criação do objeto 'DAO' que fará a conexão com o BD
- EntrevistadoDAO entDAO = new EntrevistadoDAO() ;
- if( entDAO.insere(ent) )
- limpar() ; //Veja a linha 84
- }
- //Código associado ao EVENTO do botão fechar
- private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
- System.exit(0);
- }
- // O código abaixo é referente ao EVENTO clique do botão limpar.
- private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
- limpar() ;
- }
- private void limpar(){
- jTextField1.setText("");
- jSlider1.setValue(25);
- jLabel5.setText(String.valueOf(25));
- jRadioButton1.setSelected(true);
- jRadioButton3.setSelected(true);
- }
- //Código associado ao EVENTO do botão deslizante
- private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
- // TODO add your handling code here:
- JSlider temp = (JSlider) evt.getSource() ;
- if( !temp.getValueIsAdjusting() )
- jLabel5.setText(String.valueOf(temp.getValue()));
- }
- // O código abaixo está associado ao botão Listar TextArea
- private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
- // botão LISTAR em uma TextArea
- ListarTextAreaGUI fListar = new ListarTextAreaGUI() ;
- fListar.setVisible(true);
- // Lista no modo texto
- /*
- EntrevistadoDAO entDAO = new EntrevistadoDAO() ;
- String nome[] = entDAO.lista() ;
- for( int i = 0 ; i < nome.length ; i++ )
- System.out.println( "Nome: " + nome[i]) ;
- */
- }
- //Código associado ao EVENTO do botão Listar JTable
- private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
- // botão LISTAR em JTable
- ListarJTableGUI fListarJT = new ListarJTableGUI() ;
- fListarJT.setVisible(true);
- }
- /**
- * @param args the command line arguments
- */
- public static void main(String args[]) {
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- new EntrevistadoGUI().setVisible(true);
- }
- });
- }
- // Variables declaration - do not modify
- private javax.swing.ButtonGroup buttonGroup1;
- private javax.swing.ButtonGroup buttonGroup2;
- private javax.swing.JButton jButton1;
- private javax.swing.JButton jButton2;
- private javax.swing.JButton jButton3;
- private javax.swing.JButton jButton4;
- private javax.swing.JLabel jLabel1;
- private javax.swing.JLabel jLabel2;
- private javax.swing.JLabel jLabel3;
- private javax.swing.JLabel jLabel4;
- private javax.swing.JLabel jLabel5;
- private javax.swing.JRadioButton jRadioButton1;
- private javax.swing.JRadioButton jRadioButton2;
- private javax.swing.JRadioButton jRadioButton3;
- private javax.swing.JRadioButton jRadioButton4;
- private javax.swing.JSlider jSlider1;
- private javax.swing.JTextField jTextField1;
- private javax.swing.JToggleButton jToggleButton1;
- // End of variables declaration
- }
Linha 50 do código da GUI EntrevistadoGUI.java:
Linha 67 (classe EntrevistadoDAO) do código da GUI EntrevistadoGUI.java:
Linha 23 da linha 67 (Classe ConnectionFactoryComProperties) do código da GUI EntrevistadoGUI.java:
Linha 25 da linha 23 da linha 67 (BancoDeDados.properties) do código da GUI EntrevistadoGUI.java:
Linhas 101 a 117 do código da GUI EntrevistadoGUI.java:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package modelo;
- /*
- *
- * @author Paulo Henrique Cayres
- */
- public class Entrevistado {
- private Long codigo;
- private String nome;
- private byte idade;
- private boolean fumante;
- private char sexo;
- public Entrevistado() {
- }
- public boolean isFumante() {
- return fumante;
- }
- public void setFumante(boolean fumante) {
- this.fumante = fumante;
- }
- public byte getIdade() {
- return idade;
- }
- public void setIdade(byte idade) {
- this.idade = idade;
- }
- public String getNome() {
- return nome;
- }
- public void setNome(String nome) {
- this.nome = nome;
- }
- public char getSexo() {
- return sexo;
- }
- public void setSexo(char sexo) {
- this.sexo = sexo;
- }
- }
- package modelo;
- import controle.ConnectionFactoryComProperties;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import javax.swing.JOptionPane;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class EntrevistadoDAO {
- // atributo para conexão com o BD
- private Connection con;
- // construtor do DAO estabelece a conexão com o BD
- public EntrevistadoDAO() {
- this.con = new ConnectionFactoryComProperties().getConnection();
- }
- // métodos implementados aqui são as operações CRUD desejadas
- public boolean insere(Entrevistado entrevistado) {
- String sql = "INSERT INTO entrevistado " +
- "(nome, idade, fumante, sexo) VALUES (?,?,?,?)";
- try {
- // utilização de SQL preparadada
- PreparedStatement stmt = con.prepareStatement(sql);
- // ajuste dos parâmetros (?), com o método 'get' apropriado
- stmt.setString(1, entrevistado.getNome());
- stmt.setInt(2, entrevistado.getIdade());
- stmt.setBoolean(3, entrevistado.isFumante());
- stmt.setString( 4, String.valueOf( entrevistado.getSexo()) );
- // execução da consulta
- stmt.executeUpdate();
- // encerramento do uso do canal
- stmt.close();
- JOptionPane.showMessageDialog(null,"Registro inserido com sucesso!","INFORMAÇÃO", JOptionPane.INFORMATION_MESSAGE);
- return true ;
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
- public String [] lista() {
- String sql = "SELECT * FROM entrevistado ORDER BY nome" ;
- // String [] dados = null ; // definição da estrutura de dados de retorno
- ArrayList<String> dados = new ArrayList<>() ; // definição da estrutura de dados de retorno
- try {
- Statement stmt = this.con.createStatement() ;
- ResultSet rs = stmt.executeQuery(sql);
- ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData() ;
- // percorrer o ResultSet para compor a estrutura de dados de retorno
- int idxLinha = 0;
- while(rs.next()) {
- dados.add(rs.getString("nome"));
- // e outros dados que julgar necessário
- idxLinha++;
- }
- stmt.close();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- String []retorno = new String[dados.size()];
- int i=0;
- for(String temp:dados)
- retorno[i++] = temp;
- return retorno;
- }
- // Utilização de JTable via JDBC
- public ArrayList<Object[]> listaAll( String sql ) {
- ArrayList<Object[]> dados = new ArrayList<>() ; // definição da estrutura de dados de retorno
- try {
- PreparedStatement stmt = this.con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE ) ;
- ResultSet rs = stmt.executeQuery();
- ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData() ;
- int nCols = rsmd.getColumnCount() ;
- String colunas[] = new String[nCols] ;
- for( int i = 0 ; i < nCols ; i++ ){
- colunas[i] = rsmd.getColumnName(i+1);
- }
- dados.clear() ;
- dados.add(colunas); // guardando a descrição dos campos em primeiro
- while( rs.next()){
- Object l[] = new Object[nCols] ;
- for( int i = 0 ; i < nCols; i++){
- l[i] = rs.getObject(i+1) ;
- }
- dados.add(l);
- }
- rs.close() ;
- stmt.close();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- return dados;
- }
- }
Linha 23 da linha 67 (Classe ConnectionFactoryComProperties) do código da GUI EntrevistadoGUI.java:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package controle;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.Properties;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ConnectionFactoryComProperties{
- public Connection getConnection() {
- try {
- // Criação de um objeto de propriedades
- Properties prop = new Properties();
- // leitura/carga do arquivo texto com as propriedades
- prop.load( getClass().getResourceAsStream("../util/bancoDeDados.properties"));
- // obtenção do valor de cada parâmetro através do método getProperty
- String dbDriver = prop.getProperty("db.driver");
- String dbUrl = prop.getProperty("db.url");
- String dbUser = prop.getProperty("db.user");
- String dbPwd = prop.getProperty("db.pwd");
- Class.forName(dbDriver);
- return DriverManager.getConnection(dbUrl, dbUser, dbPwd);
- } catch (ClassNotFoundException | IOException | SQLException ex) {
- throw new RuntimeException(ex);
- }
- }
- }
- db.driver=org.postgresql.Driver
- db.url=jdbc:postgresql://localhost:5432/postgres
- db.user=postgres
- db.pwd=rnpesr
Linhas 101 a 117 do código da GUI EntrevistadoGUI.java:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- /*
- * ListarTextAreaGUI.java
- *
- * Created on 24/09/2012, 13:54:39
- */
- package visao;
- import modelo.EntrevistadoDAO;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ListarTextAreaGUI extends javax.swing.JFrame {
- /** Creates new form ListarTextAreaGUI */
- public ListarTextAreaGUI() {
- initComponents();
- setTitle( "Relação de Entrevistados") ;
- EntrevistadoDAO entDAO = new EntrevistadoDAO() ;
- String nome[] = entDAO.lista() ;
- for( int i = 0 ; i < nome.length ; i++ ){
- jTextArea1.append( (i+1) + " " + nome[i] +"\n") ;
- //TESTE para verificar resultado da consulta => System.out.println( "Nome: " + nome[i]) ;
- }
- }
- /** 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")
- /**
- * @param args the command line arguments
- */
- public static void main(String args[]) {
- /* Set the Nimbus look and feel */
- //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
- /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
- * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
- */
- /* Create and display the form */
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- new ListarTextAreaGUI().setVisible(true);
- }
- });
- }
- // Variables declaration - do not modify
- private javax.swing.JScrollPane jScrollPane1;
- private javax.swing.JTextArea jTextArea1;
- // End of variables declaration
- }
Linhas 120 a 125 do código da GUI EntrevistadoGUI.java:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- /*
- * ListarJTableGUI.java
- *
- * Created on 24/09/2012, 14:27:28
- */
- package visao;
- import controle.QueryTableModel;
- import javax.swing.JTable;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ListarJTableGUI extends javax.swing.JFrame {
- /** Creates new form ListarJTableGUI */
- public ListarJTableGUI() {
- initComponents();
- // constrói o componente "tabela", com os parâmetros: colunas (título) e dados (do cursor)
- // tabela = new JTable( new QueryTableModel("SELECT * FROM entrevistado ORDER BY nome;") ) ;
- QueryTableModel qtm = new QueryTableModel("SELECT * FROM entrevistado ORDER BY nome;") ;
- tabela = new JTable( qtm ) ;
- jScrollPane1.setViewportView(tabela); // scrollpane já criado no initComp.. então atualizar com tabela
- setTitle("Exemplo de JTable com JDBC") ;
- getContentPane().add( jScrollPane1 , "Center") ;
- setDefaultCloseOperation( DISPOSE_ON_CLOSE );
- }
- /** 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")
- /**
- * @param args the command line arguments
- */
- public static void main(String args[]) {
- /* Set the Nimbus look and feel */
- //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
- /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
- * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
- */
- /* Create and display the form */
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- new ListarJTableGUI().setVisible(true);
- }
- });
- }
- // Variables declaration - do not modify
- private javax.swing.JScrollPane jScrollPane1;
- // End of variables declaration
- private JTable tabela ;
- }
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
EntrevistadoGUI:
---------------------------------------------------------------------------------------------------------
Sessão 9:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import java.sql.CallableStatement;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Types;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ExemploCallableStatement {
- public static void main(String[] args) {
- try {
- Class.forName("org.postgresql.Driver") ;
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "rnpesr");
- // Chamada da function
- CallableStatement st = connect.prepareCall("{? = CALL consultaaluno(?)}");
- st.registerOutParameter(1, Types.VARCHAR);
- st.setInt(2, 2);
- st.execute();
- if(st.getString(1) == null)
- System.out.println("Código inválido!!!");
- else
- System.out.println(st.getString(1));
- }
- catch (SQLException | ClassNotFoundException ex) {
- System.out.println(ex.toString());
- }
- }
- }
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:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import java.sql.CallableStatement;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Types;
- /**
- *
- * @author Aluno
- */
- public class ExemploConsultaAluno {
- public static void main(String[] args) {
- try {
- Class.forName("org.postgresql.Driver");
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "rnpesr");
- // Chamada da function
- CallableStatement st = connect.prepareCall("{? = CALL consultaaluno(?)}");
- st.registerOutParameter(1, Types.VARCHAR);
- st.setInt(2, 2);
- st.execute();
- javax.swing.JOptionPane.showMessageDialog(null, st.getString(1));
- } catch (SQLException | ClassNotFoundException ex) {
- System.out.println(ex.toString());
- }
- }
- }
Se o parâmetro da linha 27 fosse st.setInt(2,1) o resulta seria Paulo Cayres. No entanto, teremos o resultado abaixo:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Statement;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ExemploBatch {
- public static void main(String[] args) {
- try {
- Class.forName("org.postgresql.Driver") ;
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
- connect.setAutoCommit(false);
- try{
- Statement st = connect.createStatement()
- st.addBatch("insert into empregado(ssn, pnome, unome, sexo, dno) values('123','Paulo','Paulo','M', '1')");
- st.addBatch("insert into empregado(ssn, pnome, unome, sexo, dno) values('456','Henrique','Cayres','M', '1')");
- st.addBatch("inserte into empregado(ssn, pnome, unome, sexo, dno) values('789','Cayres','Henrique','M', '1')");
- st.executeBatch();
- connect.commit();
- }
- catch(SQLException e){
- System.out.println("Erro ao tentar incluir registros!!!\n\n"+e.toString());
- try{
- connect.rollback();
- }
- catch(SQLException ex){
- System.out.println("Erro ao tentar executar rollback!!!\n\n"+ex.toString());
- }
- }
- finally{
- try{
- connect.commit();
- connect.setAutoCommit(true);
- connect.close();
- }
- catch(SQLException ex){
- System.out.println("Erro ao tentar executar commit!!!\n\n"+ex.toString());
- }
- }
- }
- catch (SQLException | ClassNotFoundException ex) {
- System.out.println("Erro de conexão com o banco de dados!!!\n\n"+ex.toString());
- }
- }
- }
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
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Statement;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ExemploCommit {
- public static void main(String[] args) {
- try {
- Class.forName("org.postgresql.Driver") ;
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
- connect.setAutoCommit(false);
- try{
- Statement st = connect.createStatement();
- st.execute("insert into empregado(ssn, pnome, unome, sexo, dno) values('123','Paulo','Paulo','M', '1')");
- st.execute("insert into empregado(ssn, pnome, unome, sexo, dno) values('456','Cayres','Cayres','M', '1')");
- st.execute("insertw into empregado(ssn, pnome, unome, sexo, dno) values('789','Erro','Erro','M', '1')");
- }
- catch(SQLException e){
- System.out.println("Erro ao tentar incluir registros!!!\n\n"+e.toString());
- try{
- connect.rollback();
- }
- catch(SQLException ex){
- System.out.println("Erro ao tentar executar rollback!!!\n\n"+ex.toString());
- }
- }
- finally{
- try{
- connect.commit();
- connect.close();
- }
- catch(SQLException ex){
- System.out.println("Erro ao tentar executar commit!!!\n\n"+ex.toString());
- }
- }
- }
- catch (SQLException | ClassNotFoundException ex) {
- System.out.println("Erro de conexção com o banco de dados!!!\n\n"+ex.toString());
- }
- }
- }
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
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import coreservlets.DBResults;
- import coreservlets.DatabaseUtilities;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ExemploDatabaseUtilities {
- public static void main(String[] args) {
- try {
- Class.forName("org.postgresql.Driver") ;
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
- //uso de DBResults
- DBResults teste = DatabaseUtilities.getQueryResults(connect, "select * from empregado", false) ;
- System.out.println(teste.toHTMLTable(null));
- //uso de DatabaseUtilities
- DatabaseUtilities.printTable(connect, "empregado", 40, true);
- DatabaseUtilities.printTableData("empregado", teste, 40, true);
- }
- catch (SQLException | ClassNotFoundException ex) {
- System.out.println("Erro de conexção com o banco de dados!!!\n\n"+ex.toString());
- }
- }
- }
O resultado do código acima será mais ou menos o que está nas telas abaixo:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import java.sql.CallableStatement;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Types;
- /**
- *
- * @author paulo983
- */
- public class ExemploIsValidUser {
- public static void main(String[] args) {
- try {
- Class.forName("org.postgresql.Driver") ;
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
- // Chamada da function
- CallableStatement st = connect.prepareCall("{? = CALL isvaliduser(?,?)}");
- st.registerOutParameter(1, Types.BOOLEAN);
- st.setString(2, "cayres");
- st.setString(3, "1234");
- st.execute();
- if(st.getBoolean(1))
- System.out.println("Acesso Liberado!");
- else
- System.out.println("Acesso Negado!");
- }
- catch (SQLException | ClassNotFoundException ex) {
- System.out.println(ex.toString());
- }
- }
- }
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
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import java.sql.Connection;
- import java.sql.DatabaseMetaData;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ExemploMetaData {
- public static void main(String[] args){
- try {
- Class.forName("org.postgresql.Driver") ;
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432", "postgres", "rnpesr");
- //procurar informações sobre o banco de dados como um todo
- DatabaseMetaData dbMetaData = connect.getMetaData();
- System.out.println("Banco de Dados: "+ dbMetaData.getDatabaseProductName());
- System.out.println("Versão do Banco de Dados: "+ dbMetaData.getDatabaseProductVersion());
- }
- catch (SQLException | ClassNotFoundException ex) {}
- }
- }
Teremos como resultado o seguinte:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.sql.Statement;
- /**
- *
- * @author paulo983
- */
- public class ExemploMetaDataTabela {
- public static void main(String[] args) {
- try {
- Class.forName("org.postgresql.Driver") ;
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
- //SQL que retorna todos os empregados em ordem alfabética
- Statement st = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
- String query = "select * from aluno order by nome";
- ResultSet rs = st.executeQuery(query);
- ResultSetMetaData rsMetaData = rs.getMetaData();
- // abtendo informações sobre o result set
- for(int i=1; i <= rsMetaData.getColumnCount(); i++){
- System.out.println(rsMetaData.getColumnName(i) + " - " +
- rsMetaData.getColumnTypeName(i) + " - " +
- rsMetaData.getPrecision(i) + " - " +
- rsMetaData.getColumnDisplaySize(i) + " - " +
- rsMetaData.isCaseSensitive(i) + " - " +
- rsMetaData.isCurrency(i) + " - " +
- rsMetaData.isDefinitelyWritable(i) + " - " +
- rsMetaData.isNullable(i) + " - " +
- rsMetaData.isReadOnly(i) + " - " +
- rsMetaData.isSearchable(i) + " - " +
- rsMetaData.isWritable(i) + " - " +
- rsMetaData.isAutoIncrement(i));
- }
- // percorrendo o result set
- System.out.println("--------------------------");
- rs.beforeFirst();
- while(rs.next()){
- System.out.println(rs.getString("nome"));
- }
- }
- catch (SQLException | ClassNotFoundException ex) {
- System.out.println(ex.toString());
- }
- }
- }
Segue o resultado da execução do código acima:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import java.sql.CallableStatement;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Types;
- /**
- *
- * @author paulo983
- */
- public class ExemploStoredProcedure {
- public static void main(String[] args) {
- try {
- Class.forName("org.postgresql.Driver") ;
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/empresa", "postgres", "rnpesr");
- // Chamada da function
- CallableStatement st = connect.prepareCall("{? = CALL maiuscula(?)}");
- st.registerOutParameter(1, Types.VARCHAR);
- st.setString(2, "Renato Bueno");
- st.execute();
- System.out.println(st.getString(1));
- }
- catch (SQLException | ClassNotFoundException ex) {
- System.out.println(ex.toString());
- }
- }
- }
Teremos como resultado o seguinte:
O código abaixo se refere a procedure ( no postgree procedure é sinônimo de function):
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import java.sql.CallableStatement;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Types;
- import javax.swing.JOptionPane;
- /**
- *
- * @author Aluno
- */
- public class exercicioValidaUser extends javax.swing.JFrame {
- /**
- * Creates new form exercicioValidaUser
- */
- public exercicioValidaUser() {
- 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")
- private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- try {
- Class.forName("org.postgresql.Driver");
- Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "rnpesr");
- // Chamada da function
- CallableStatement st = connect.prepareCall("{? = CALL isvaliduser(?,?)}");
- st.registerOutParameter(1, Types.BOOLEAN);
- st.setString(2, jTextField1.getText());
- String pass = new String(jPasswordField1.getPassword());
- st.setString(3, pass);
- st.execute();
- if (pass.equals("1234")) {
- javax.swing.JOptionPane.showMessageDialog(null, "Acesso liberado", "Logon", JOptionPane.WARNING_MESSAGE);
- } else {
- javax.swing.JOptionPane.showMessageDialog(null, "Acesso negado", "Logon", JOptionPane.OK_OPTION);
- }
- } catch (SQLException | ClassNotFoundException ex) {
- System.out.println(ex.toString());
- }
- }
- /**
- * @param args the command line arguments
- */
- public static void main(String args[]) {
- /* Create and display the form */
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- new exercicioValidaUser().setVisible(true);
- }
- });
- }
- // Variables declaration - do not modify
- private javax.swing.JButton jButton1;
- private javax.swing.JLabel jLabel1;
- private javax.swing.JLabel jLabel2;
- private javax.swing.JPasswordField jPasswordField1;
- private javax.swing.JTextField jTextField1;
- // End of variables declaration
- }
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
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- import controle.AlunoDAO;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import modelo.Aluno;
- /**
- *
- * @author paulo983
- */
- public class ExemploLoginAluno extends javax.swing.JFrame {
- /**
- * Creates new form ExemploLoginAluno
- */
- public ExemploLoginAluno() {
- 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")
- private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- Aluno a = new Aluno(jTextField1.getText(),
- new String(jPasswordField1.getPassword()));
- AlunoDAO teste;
- try {
- teste = new AlunoDAO();
- if(teste.isValidUser(a))
- javax.swing.JOptionPane.showMessageDialog(null, "Acesso Liberado!");
- else
- javax.swing.JOptionPane.showMessageDialog(null, "Acesso Negado!");
- } catch (Exception ex) {
- Logger.getLogger(ExemploLoginAluno.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- /**
- * @param args the command line arguments
- */
- public static void main(String args[]) {
- /* Create and display the form */
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- new ExemploLoginAluno().setVisible(true);
- }
- });
- }
- // Variables declaration - do not modify
- private javax.swing.JButton jButton1;
- private javax.swing.JButton jButton2;
- private javax.swing.JLabel jLabel1;
- private javax.swing.JLabel jLabel2;
- private javax.swing.JPasswordField jPasswordField1;
- private javax.swing.JTextField jTextField1;
- // End of variables declaration
- }
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:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package modelo;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class Aluno {
- private int idAluno;
- private String nome;
- private String usuario;
- private String senha;
- public Aluno() {
- }
- public Aluno(String usuario, String senha) {
- this.usuario = usuario;
- this.senha = senha;
- }
- public Aluno(int idAluno, String nome, String usuario, String senha) {
- this.idAluno = idAluno;
- this.nome = nome;
- this.usuario = usuario;
- this.senha = senha;
- }
- public int getIdAluno() {
- return idAluno;
- }
- public void setIdAluno(int idAluno) {
- this.idAluno = idAluno;
- }
- public String getNome() {
- return nome;
- }
- public void setNome(String nome) {
- this.nome = nome;
- }
- public String getUsuario() {
- return usuario;
- }
- public void setUsuario(String usuario) {
- this.usuario = usuario;
- }
- public String getSenha() {
- return senha;
- }
- public void setSenha(String senha) {
- this.senha = senha;
- }
- }
----------------------------------------------------------------
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package controle;
- import java.sql.CallableStatement;
- import java.sql.Connection;
- import java.sql.SQLException;
- import java.sql.Types;
- import modelo.Aluno;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class AlunoDAO {
- private Connection con;
- public AlunoDAO() throws Exception {
- this.con = new ConnectionFactoryComProperties().getConnection();
- }
- public boolean isValidUser(Aluno a ){
- try {
- CallableStatement st = con.prepareCall("{? = CALL isvaliduser(?,?)}");
- // Chamada da function
- st.registerOutParameter(1, Types.BOOLEAN);
- st.setString(2, a.getUsuario());
- st.setString(3, a.getSenha());
- st.execute();
- return st.getBoolean(1);
- }
- catch (SQLException ex) {
- System.out.println(ex.toString());
- return false;
- }
- }
- }
A função isvaliduser da linha 28 é a seguinte:































 
No comments:
Post a Comment