I have two methods to do a validation like leave in only one?

Asked

Viewed 34 times

-1

connection class:

public class ConnectionFactory {

    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/helpsemeq"+"?verifyServerCertificate=false&useSSL=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=America/Sao_Paulo";
    private static final String USER = "root";
    private static final String PASS = "";
    private static Connection conexao;
    public Statement statement;
    public ResultSet resultset;

    public boolean getConnection() {
        boolean result = true;
        try {
            Class.forName(DRIVER);
            conexao = DriverManager.getConnection(URL, USER, PASS);
            result = true;
        } catch (ClassNotFoundException | SQLException ex) {
            result = false;
            throw new RuntimeException("Erro na conexão: ", ex);
        }
        return result;
    }

    public static void closeConnection(Connection con) {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void closeConnection(Connection con, PreparedStatement stmt) {
        closeConnection(con);
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void closeConnection(Connection con, PreparedStatement stmt, ResultSet rs) {
        closeConnection(con, stmt);
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void executeSQL(String sql) {
        try {
            statement = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            resultset = statement.executeQuery(sql);
        } catch (SQLException sqlex) {
            System.out.println("Não foi possivel executar o comando: \n" + sqlex + "\n o sql passado foi: \n" + sql);
        }
    }
}

here is the method that is in the connection class to run the query:

public void executeSQL(String sql) {
        try {
            statement = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            resultset = statement.executeQuery(sql);
        } catch (SQLException sqlex) {
            System.out.println("Não foi possivel executar o comando: \n" + sqlex + "\n o sql passado foi: \n" + sql);
        }
    }

the other method that gets inside the jframe:

public void validaLogin(){
        try {
            ConnectionFactory conn = new ConnectionFactory();
            conn.getConnection();

            String sql = "SELECT login,senha FROM usuario where login = '" + jTextField1.getText() + "' and  senha = '" + jTextField2.getText() + "'";
            conn.executeSQL(sql);

            //Se houver resultado, ou seja, se validar o usuario e senha, faça algo.
            if (conn.resultset.next()) {
                new NewJFrame1().setVisible(true);
                dispose();
            } else {
                System.out.println("Acesso negado.");
            }
        }catch(SQLException e){
            System.out.println("Erro: "+e);
        }
    }

it would be possible to do all this in just one method?

  • I’m sorry but I don’t quite understand your question. Is the validation you say authentication? And why only one method?

  • Yes that, has the method in the connection class and in the class of jframe, I wanted to put in only one method, because I aim to also save the id in the query, after the login it will go to a screen where it will be possible to add or change values and then wanted to save the user id to change in the database according to the user id. ( ex has table user, has requests table, requests will receive the id_login) and then when to change or add a request after being logged in save with the logged in id_login.

  • Lega, I get it. I think it’s cool your code. Maybe, an improvement I can suggest, is to create two more classes. User and user. The User class would store id and the User class(Data Access Objetct) would provide an instance of the User class with id. If you want I can answer by showing how the classes could be.

  • @rafaelim would be very grateful bro, and if you could point me something to study more about these interactions with comics, I’m studying s.i, but so far only gave java and had no interaction with comics :(

1 answer

1


I think it’s really cool your code. My suggestion is to create two more classes. User and User

A User object will be used to store the id.

An object of the User type will be responsible for accessing the database using the Connectionfactory you created. An example would be:

class Usuario {
    Long id;
    public Usuario(Long id) {
        this.id = id;
    }
}

class UsuarioDAO {

    private ConnectionFactory connectionFactory;

    public UsuarioDAO {
        this.connectionFactory = connectionFactory;    
    }

    public User autentica(String login, String senha) {
        String query = ...// O código para montar a query
        this.connectionFactory.getConnection();
        this.connectionFactory.executeSql(query);
        ResultSet rs = this.connectionFactory.resultset;
        if (rs.next()) {
            Usuario usuario = new Usuario(rs.getLong("id"));
            return usuario;
        }
        return null; //Se for null, quer dizer que não foi possível autenticar
    }
}

And so, in Jframe you use the user.

It’s nice to do this separation to make your code less coupled and more cohesive. It has some principles of Object-Oriented Programming that deal with coupling and cohesion. DRY, SOLID, Tell Don’t Ask are some. Worth a look at!

On BD access indications, I suggest the same google. Search for JDBC(Java Database Connectivity) that you will find many subjects, frameworks and library to work with.

Good luck!

  • @rafaellim man can you give me one more help Manin? I’m c a small problem (I believe)

  • Oops, you can talk.

  • opa man with respect to this code every time I login he will save the id with even if I change screen?

  • Because I was thinking of making a screen to give some Insert’s and would need the id of that logged in user.

  • if you take a look at this topic : https://answall.com/questions/391457/d%C3%Bavidas-ao-aplicar-um-metodo-dao

  • Opa, sorry for the delay to answer you. I was in a week of training here. If you are using Jframe, yes. If I’m not mistaken, he keeps in his memory all the objects you’re using.

Show 1 more comment

Browser other questions tagged

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