Java + SQL

Bom dia pessoal.

Estou com problemas no desenvolvimento de um sisteminha simples de suporte para testes.

Eu tenho uma tela de Login que recebe usuário e senha, ele faz a conexão e vai verificar no banco se o usuário e senha conferem:

  • Primeiro ele verifica se usuário existe, se sim, verifica se a senha para o usuário está correta, então prossegue.

Problema é que não sei como fazer isso, por exemplo.
Queria enviar uma procedure feita no banco que tem um Select ID from tabela Where Nome = PARAMETRO.
Ele precisa me retornar um true pelo menos, algo assim…NO JAVA.
Senha mesma coisa, como faço isso?

Obrigado.

Algo que já está pronto:

public void Verificar(String Nome, String Senha) //Aqui passei um Campo texto para confirmar usuario e outro senha.
{
        String usuario = "usp_usuario ?"; //Esta é a procedure que criei com o Select e precisa retornar algo.
        try{
            p.setString(1, Nome);
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(usuario);
           }
        catch(SQLException e){}
        if(usuario.equals(Nome)) //Se o usuario que retornou for igual ao campo texto digitado.
             {
                   String senha = "usp_senha ?"
                     p.setString(1, Senha);
                     Statement st = con.createStatement();
                     ResultSet rs = st.executeQuery(senha);
             }
}

    
    }

O código do select da senha, por exemplo é:

“select Senha from tblFormulario where Senha = ? and Nome = ?”;

Espero que lhe ajude.

    public CModeloLogin PesquisarLogin(String Login, String Senha)  {

        Connection con = Conectar();
        PreparedStatement pstmt;
        CModeloLogin loginEncontrado = null;

        try {

            pstmt = con.prepareStatement("select fu.codigo_fun, fu.nome_fun from funcionario_login fl, funcionario fu where login_logf = ? and senha_logf = ? and fl.codfun_logf = fu.codigo_fun and ativo_logf = 'S'");
            pstmt.setString(1, Login);
            pstmt.setString(2, Senha);

            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                loginEncontrado = new CModeloLogin();
                loginEncontrado.setCodFuncionario(Integer.parseInt(rs.getString("fu.codigo_fun")));
                loginEncontrado.setNomeFuncionario(rs.getString("fu.nome_fun"));
            }
            
        } catch (Exception e) {
        }

        return loginEncontrado;
    }

Acrescentando a linha do Scorsatto, tentei simplificar o codigo e não utilizar o objeto, julgo ser uma forma simples para entender,
após :

private boolean validaLoginSenha(String usuario, String senha) {
        try {
            ResultSet rs = conn.createStatement().executeQuery("SELECT c_nom_usu,c_sen_usu "
                                                             + "FROM cadusuario "
                                                             + "WHERE c_log_usu ='" + usuario + "' "
                                                             + "AND c_sen_usu ='" + senha + "'");
            if (rs.next()) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException ex) {
           }
        return false;
    }

Caso queira melhorar, retorne o objeto com os dados.

Bom dia.

Tenho um problema, não sei onde está o erro…Vamos lá:
Meu Login.Java:

package suporte;

public class Login extends javax.swing.JFrame {
   
    public Login() {
        initComponents();
    }

    conexao con = new conexao();
    Banco bco = new Banco();


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        btConectar = new javax.swing.JButton();
        btLimpar = new javax.swing.JButton();
        userTxt = new javax.swing.JTextField();
        passTxt = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Perpetua Titling MT", 0, 11));
        jLabel1.setText("Login");

        jLabel2.setText("Usuario:");

        jLabel3.setText("Senha:");

        btConectar.setText("Conectar");
        btConectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConectarActionPerformed(evt);
            }
        });

        btLimpar.setText("Limpar");
        btLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLimparActionPerformed(evt);
            }
        });

        userTxt.setText("jTextField1");
        userTxt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                userTxtActionPerformed(evt);
            }
        });

        passTxt.setText("jTextField2");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(175, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(182, 182, 182))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(passTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(userTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(134, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(224, Short.MAX_VALUE)
                .addComponent(btConectar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btLimpar)
                .addGap(20, 20, 20))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(userTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btConectar)
                    .addComponent(btLimpar)))
        );

        userTxt.getAccessibleContext().setAccessibleName("campoUser");
        passTxt.getAccessibleContext().setAccessibleName("campoPass");

        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()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

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

    [b]private void btConectarActionPerformed(java.awt.event.ActionEvent evt) {                                           
         if(con.fazConexao() != null)
         {
             if(bco.Verificar(userTxt.getText(), passTxt.getText()));

                    new Registrar().setVisible(true);
                    dispose();    
         }
    }                                          [/b]    
[b]private void btLimparActionPerformed(java.awt.event.ActionEvent evt) {                                         
passTxt.setText("");
userTxt.setText("");
    }                                        [/b]    private void userTxtActionPerformed(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 Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btConectar;
    private javax.swing.JButton btLimpar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField passTxt;
    private javax.swing.JTextField userTxt;
    // End of variables declaration                   

}

Minha classe para conexão:

package suporte;

import java.sql.Connection;
import java.sql.DriverManager;


public class conexao {
	private Connection con;

	public Connection fazConexao(){
		try{
                    con = null;
                    String conectando = "jdbc:sqlserver://localhost:1433;databaseName=Suporte;";

			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                        con = DriverManager.getConnection(conectando,"sa","111");
                        System.out.println("Conexão feita com sucesso!");
			
		}
		catch(Exception e){
                        e.printStackTrace();
                        System.err.println(e.getMessage());
                                  }
                return con;
    }
                    
		
	

	public void fecharConexao(){
		try {
			con.close();

		} catch (Exception e) {
		}
	}
}

E a classe do Banco:


package suporte;

import java.sql.*;


public class Banco {

    Connection con;
    Formulario form;
    
//--------------------------------------------------------------------------------------------//
    //------------------------------------------------------------------------------------//
    public void inserir(String nome, String setor, String problema, String dataRegistro) {
		String comando = "insert into tabela1 (nome, setor, problema, dataRegistro) values(?,?,?,?)";

		PreparedStatement p;
		try {

			p = this.con.prepareStatement(comando);
			p.setString(1, form.getNome());
			p.setString(2, form.getSetor());
			p.setString(3,form.getProblema());
			p.setDate(4,  new java.sql.Date( form.getDataRegistro().getTime() )  );


			p.execute();



		} catch (SQLException e) {
		}
    }

    public void Verificar(String Nome, String Senha){

        String usuario = "usp_usuario ?";
        String senha = "usp_senha ?";
        PreparedStatement p = null;
        try{
            p.setString(1, Nome);
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(usuario);
           }
        catch(SQLException e){}
        if(usuario.equals(Nome)){
            try{
                   p.setString(1, Senha);
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(senha);
            }
            catch(SQLException e){}
            //String senha = "select Senha from tblFormulario where Senha = ? and Nome = ?";
        }


        
    private boolean Verificar(String Usuario, String Senha) {
        try {
            ResultSet rs = con.createStatement().executeQuery("SELECT c_nom_usu,c_sen_usu "
                                                             + "FROM cadusuario "
                                                             + "WHERE c_log_usu ='" + Usuario + "' "
                                                             + "AND c_sen_usu ='" + Senha + "'");
            if (rs.next()) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException ex) {}
        return false;
    }

//------------------------------------------------------------------------------------------//
                //---------------------------------------------------------//

public Formulario Tudo() {

		
		String comando = "select * from Contato";

		try {

			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery(comando);

			while( rs.next()){
				

				int protocolo = rs.getInt("protocolo");
				String nome = rs.getString("nome");
				String setor = rs.getString("setor");
				String problema = rs.getString("problema");
				Date dataRegistro = rs.getDate("dataRegistro");


				form.setProtocolo(protocolo);
                                form.setNome(nome);
				form.setSetor(setor);
				form.setProblema(problema);
				form.setDataRegistro(dataRegistro);

                                


				
			}
                        return form;

		} catch (Exception e) {
		}

		return null;
	}


	}
   

Estou com um erro de parametros, de tipo, não sei no Verificar.
Por ser Boolean, passar parametros, não estou conseguindo decifrar o problema aqui.

Qual o erro? Em que ponto ele acontece?..

pq não debug e veja aonde esta ocorredo o evento ,se achar post que ajudamos

abrxx!!!

private boolean Verificar(String Usuario, String Senha) { try { ResultSet rs = con.createStatement().executeQuery("SELECT c_nom_usu,c_sen_usu " + "FROM cadusuario " + "WHERE c_log_usu ='" + Usuario + "' " + "AND c_sen_usu ='" + Senha + "'"); if (rs.next()) { return true; } else { return false; } } catch (SQLException ex) {} return false; }

Não tem como descobrir o erro se você não postar a exception
bem quanto ao código acima… não utilize " + Usuário + "
de uma olhada em SQL Injection e vai ver o pq de não utilizar…
bem e pelo código Login.java que vc postou vc deve estar utilizando o NetBeans certo ?

Correto, NetBeans.

O que ocorre.

Vou colocar no btConectar o código:

if(bco.Verificar(userTxt.getText(), passTxt.getText())){
new Registrar().setVisible(true);
                    dispose(); 
}

Ele não mostra o método Verificar criado.
Ele diz para criar Verificar em Banco.java e já está criado.

Atente que Verificar() é do tipo Private.
Justificando, quando postei o codigo de login não me prendi em como mostrar o sql ou algo do genero,
e sim contribuir com a dúvida sobre o retorno, então corrigindo:

public boolean Verificar(String consulta) {  
        try {  
            ResultSet rs = con.createStatement().executeQuery(consulta);  
            if (rs.next()) {  
                return true;  
            } else {  
                return false;  
            }  
        } catch (SQLException ex) {}  
        return false;  
    }  

Você deve ajustar o codigo para sua aplicação.

Nem tinha visto, sério!!

Obrigado…

Desculpe o descuido.

Fiz algumas alterações neste e em outros códigos, criei já as telas e tal, mas estou com outro problema:

    public boolean Verificar(String Usuario, String Senha) {
        try {
            JOptionPane.showMessageDialog(null, Senha);
            JOptionPane.showMessageDialog(null, Usuario);
            ResultSet rs = con.createStatement().executeQuery("SELECT Nome, Senha FROM tblUsuario WHERE Nome ='" + Usuario + "' AND Senha ='" + Senha + "'");
            if (rs.next()) {
                return true;
                           } else {
                return false;
            }
        } catch (SQLException ex) {return false;}
        
        
    }

Coloquei os JOp. pra mostrar se ele realmente está com os valores ainda e ele me mostra os valores corretos.

Aí ele me da os seguintes erros:
Conexão feita com sucesso!
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
at suporte.Banco.Verificar(Banco.java:42)
at suporte.Login.btConectarActionPerformed(Login.java:131)
at suporte.Login.access$000(Login.java:3)
at suporte.Login$1.actionPerformed(Login.java:41)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6134)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5899)
at java.awt.Container.processEvent(Container.java:2023)
at java.awt.Component.dispatchEventImpl(Component.java:4501)
at java.awt.Container.dispatchEventImpl(Container.java:2081)
at java.awt.Component.dispatchEvent(Component.java:4331)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4301)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3895)
at java.awt.Container.dispatchEventImpl(Container.java:2067)
at java.awt.Window.dispatchEventImpl(Window.java:2458)
at java.awt.Component.dispatchEvent(Component.java:4331)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
CONSTRUÍDO COM SUCESSO (tempo total: 12 segundos)

O código do conectar ficou assim:

  private void btConectarActionPerformed(java.awt.event.ActionEvent evt) {                                           
         if(con.fazConexao() != null)
         {
             if(bco.Verificar(userTxt.getText(),passTxt.getText()) == true)
             {
                    new Registrar().setVisible(true);
                    dispose();
             }
         }
    } 
public void Verificar(String Nome, String Senha){   
  
        String usuario = "usp_usuario ?";   
        String senha = "usp_senha ?";   
        PreparedStatement p = null;   
        try{   
            p.setString(1, Nome);   
            Statement st = con.createStatement();   
            ResultSet rs = st.executeQuery(usuario);   
           }   
        catch(SQLException e){}   
        if(usuario.equals(Nome)){   
            try{   
                   p.setString(1, Senha);   
            Statement st = con.createStatement();   
            ResultSet rs = st.executeQuery(senha);   
            }   
            catch(SQLException e){}   
            //String senha = "select Senha from tblFormulario where Senha = ? and Nome = ?";   
        }   

cara pelo erro parece que o problema é nesse método aqui…
ali quando vc postou a sua classe inteira na linha 42 é isso…

Statement st = con.createStatement();

verifique se o “con” está nulo

Opa!!

O método não está mais assim, ele está desta forma:


    public boolean Verificar(String Usuario, String Senha) {
        try {
            JOptionPane.showMessageDialog(null, Senha);
            JOptionPane.showMessageDialog(null, Usuario);
            ResultSet rs = con.createStatement().executeQuery("SELECT Nome, Senha FROM tblUsuario WHERE Nome ='" + Usuario + "' AND Senha ='" + Senha + "'");
            if (rs.next()) {
                return true;
                           } else {
                return false;
            }
        } catch (SQLException ex) {return false;}
        
        
    }

[quote=Thiago0803]Fiz algumas alterações neste e em outros códigos, criei já as telas e tal, mas estou com outro problema:

    public boolean Verificar(String Usuario, String Senha) {
        try {
            JOptionPane.showMessageDialog(null, Senha);
            JOptionPane.showMessageDialog(null, Usuario);
            ResultSet rs = con.createStatement().executeQuery("SELECT Nome, Senha FROM tblUsuario WHERE Nome ='" + Usuario + "' AND Senha ='" + Senha + "'");
            if (rs.next()) {
                return true;
                           } else {
                return false;
            }
        } catch (SQLException ex) {return false;}
        
        
    }

Coloquei os JOp. pra mostrar se ele realmente está com os valores ainda e ele me mostra os valores corretos.

Aí ele me da os seguintes erros:
Conexão feita com sucesso!
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
[color=red]at suporte.Banco.Verificar(Banco.java:42)[/color]
[color=red]at suporte.Login.btConectarActionPerformed(Login.java:131)[/color]
at suporte.Login.access$000(Login.java:3)
at suporte.Login$1.actionPerformed(Login.java:41)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6134)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5899)
at java.awt.Container.processEvent(Container.java:2023)
at java.awt.Component.dispatchEventImpl(Component.java:4501)
at java.awt.Container.dispatchEventImpl(Container.java:2081)
at java.awt.Component.dispatchEvent(Component.java:4331)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4301)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3895)
at java.awt.Container.dispatchEventImpl(Container.java:2067)
at java.awt.Window.dispatchEventImpl(Window.java:2458)
at java.awt.Component.dispatchEvent(Component.java:4331)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
CONSTRUÍDO COM SUCESSO (tempo total: 12 segundos)

O código do conectar ficou assim:

private void btConectarActionPerformed(java.awt.event.ActionEvent evt) { if(con.fazConexao() != null) { if(bco.Verificar(userTxt.getText(),passTxt.getText()) == true) { new Registrar().setVisible(true); dispose(); } } } [/quote]

Verifique as 2 linhas em vermelho
você deve estar passando algum parâmetro Nulo