How to extract String from a database query?

Asked

Viewed 42 times

-2

inserir a descrição da imagem aqui

I am implementing a query screen, the user will have to enter the name and after the fields below will have to be filled in. My question is how to perform the consultation? I tried to make Select like this :

 private void consultarBtnActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        if(nomeTxt.getText().equals(""))
        {
            JOptionPane.showMessageDialog(null,"Informe o nome para realizar a consulta!");
        }
        else
        {
          
             try {
            // TODO add your handling code here:
            Connection conexao= new bancoDeDados().getConnection();
            Statement estado = conexao.createStatement();
              String sql= "select * from inquilinos where nome='"+nomeTxt.getText()+"';";
              
              
            PreparedStatement statement= conexao.prepareStatement(sql);
            
            
            statement.execute();
            cpfTxt.setText(sql);
            conexao.close();
        } catch (SQLException ex) {
            Logger.getLogger(CadastroDeUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
             
             
         }
        
    }    

I wanted to see with you how to do and how to replace this part

cpfTxt.setText(sql);

  • 2

    Not directly related, but finally: do not concatenate the fields directly in the query, as this leaves the application vulnerable to attacks from SQL Injection. Instead, prefer to set the values in PreparedStatement: https://answall.com/a/99625/112052

1 answer

0

I got the code looked like this (you have to use the resultset) :

. . .

Connection conexao= new bancoDeDados().getConnection();
            
              String sql= "select * from inquilinos where nome='"+nomeTxt.getText()+"';";
              
              
            PreparedStatement statement= conexao.prepareStatement(sql);
            ResultSet rs= statement.executeQuery();
            rs.next();
        

. . .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.