Is it necessary to put the element type inside the try?

1

When optimizing my JDBC code I started using a condition inside the 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 it does not see the variable PreparedStatement stmt; not recognizing it as a type. I want to know if I have to declare the type of the variable being it already declared in my class.

    
asked by anonymous 20.08.2015 / 20:26

2 answers

1
  

Is it necessary to put the type of the element inside the try?

Yes. But there are more things to fix in your code.

In this line you have two problems:

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

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

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

Another important thing to note is that it is not necessary to call close() of stmt , as try with resources takes care of it.

So 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% w / out% also needs either try or catch() , but you may have omitted because it is an example.

    
20.08.2015 / 20:53
1

In this example , from the Oracle site, it implements try-with-resources .

Some things to watch:

  • This feature is available starting with version 1.7 of Java.
  • It puts the type of the variable inside the parenthesis.
  • From what I've noticed, the declaration of the variable is made completely within the parenthesis of try because the scope of it is just inside try . It will not be used outside. Therefore it is declared as "resource" of try-with-resource
  • 20.08.2015 / 20:40