Is it necessary to place the element type inside the Try?

Asked

Viewed 68 times

1

When optimizing my JDBC code I started using a condition within Try.

    /** Função PreparedStatement stmt */
public PreparedStatement stmt;
/** Funçãoo ResultSet rs */
public ResultSet rs;

/** Método LoginDao - construtor */
public LoginDao() {
    super();
}

public long adiciona(Object object) {
    try {
        if (object.getClass() != new Login().getClass()) {
            throw new RuntimeException();
        }
        Login login = (Login) object;
        // Inserção Banco de Dados
        String sql = "INSERT INTO login "
                + "(email, senha, privilegio,ultimo_acesso,cpf)"
                + " VALUES (?,?,?,?,?)";
        try(stmt = getConnection().prepareStatement(sql)){}
        // prepared statement para inser��o
        stmt = getConnection().prepareStatement(sql);
        // criptografa os dados
        String emailCriptografado = new CriptografiaUniDirecional()
                .criptografar(login.getEmail());
        String senhaCriptografada = new CriptografiaUniDirecional()
                .criptografar(login.getSenha());
        System.out.println(emailCriptografado);
        System.out.println(senhaCriptografada);
        // verifica se este email ja esta cadastrado
        if (emailJaCadastrado(emailCriptografado) == false) {
            /** seta os valores */
            stmt.setString(1, emailCriptografado);
            stmt.setString(2, senhaCriptografada);
            stmt.setInt(3, login.getPrivilegio());
            // Calendar cal = Calendar.getInstance();
            Date data = new Date(System.currentTimeMillis());
            stmt.setDate(4, data);
            stmt.setString(5, login.getCpf());
            stmt.execute();
        } else {
            stmt.close();
            return 1L;
        }
        stmt.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return -1L;
}

But he doesn’t see the variablePreparedStatement stmt; not recognizing it as a type. I wonder if I have to declare the type of the variable being that it is already declared in my class.

  • Put the code where you declare the variable.

  • public Preparedstatement stmt; public Resultset rs; The code was running nice. However when trying to optimize and put it in Try the error object

  • Dude, put in the question all the relevant code in your class. Only with a line of code can’t help you.

  • Puts the entire declaration of your method @Victorhenrique

2 answers

1

In this example, of the Oracle website, it implements the try-with-resources.

Some things to be observed:

  1. This feature is available from version 1.7 of Java.
  2. It puts the type of the variable inside the parenthesis.
  3. From what I observed, the variable declaration is made in full within the parenthesis of the try because the Its scope is only within the Try. It will not be used outside. So it is declared as "resource" of try-with-resource

1


It is necessary to place the element type inside the Try?

Yes. But there’s more to fix in your code.

On that line there are two problems:

try(stmt = getConnection().prepareStatement(sql)){}

What you had previously suspected would generate error, which is the need to declare the variable with your type PreparedStatement and also the fact that you accidentally closed the try right away.

try(PreparedStatement stmt = getConnection().prepareStatement(sql)){

Another important thing to note is that it is not necessary to call the close() of stmt, since Try with Resources takes care of it.

Therefore, your code should look like this:

try {
    if (object.getClass() != new Login().getClass()) {
        throw new RuntimeException();
    }
    Login login = (Login) object;
    // Inserção Banco de Dados
    String sql = "INSERT INTO login "
            + "(email, senha, privilegio,ultimo_acesso,cpf)"
            + " VALUES (?,?,?,?,?)";
    try(PreparedStatement stmt = getConnection().prepareStatement(sql)){
        // prepared statement para inser��o
        stmt = getConnection().prepareStatement(sql);
        // criptografa os dados
        String emailCriptografado = new CriptografiaUniDirecional()
                .criptografar(login.getEmail());
        String senhaCriptografada = new CriptografiaUniDirecional()
                .criptografar(login.getSenha());
        System.out.println(emailCriptografado);
        System.out.println(senhaCriptografada);
        // verifica se este email ja esta cadastrado
        if (emailJaCadastrado(emailCriptografado) == false) {
            /** seta os valores */
            stmt.setString(1, emailCriptografado);
            stmt.setString(2, senhaCriptografada);
            stmt.setInt(3, login.getPrivilegio());
            // Calendar cal = Calendar.getInstance();
            Date data = new Date(System.currentTimeMillis());
            stmt.setDate(4, data);
            stmt.setString(5, login.getCpf());
            stmt.execute();
        } else {
            return 1L;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return -1L;
}

Note that in addition your try from outside also need or a catch() or a finally(), but it is possible that you have omitted because it is an example.

  • Yes. I edited the code to illustrate the error. Thank you for the answer.

Browser other questions tagged

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