Searching another method variable of the same Class

Asked

Viewed 1,572 times

1

I have a class BancoDeDados and it contains two methods: conexao and addDespesa. The method conexao connects to my local database. The method addDespesa adds values in one of my tables, but cannot "catch" the variable of type Statement whose name is mysql.

public class BancoDeDados {
    public void conexao(){
        try {
            System.out.println("Conectando ao Banco de Dados..");
            Class.forName("com.mysql.jdbc.Driver");
            Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost:3306/despesas?useSSL=true","root","local");
            Statement mysql = conexao.createStatement();
            System.out.println("Conectado. \n");
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("Erro na Conexão");
        }
    }

    public void addDespesa(String addDesp){
        String sqlInsert;
        sqlInsert = "insert into tipo_de_despesa(descricao) values ('"+addDesp+"')";
        mysql.execute(sqlInsert);
    }

}

1 answer

3


You can’t because of scope of the variable. You created the variable as being local within the method conexão() - It will only exist in there. If, by chance, you want the variable to be accessible in every class, you need to increase its scope, making it a class variable:

public class BancoDeDados {

    private Statement mysql;

    public void conexao(){
        try {
            System.out.println("Conectando ao Banco de Dados..");
            Class.forName("com.mysql.jdbc.Driver");
            Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost:3306/despesas?useSSL=true","root","local");
            this.mysql = conexao.createStatement();
            System.out.println("Conectado. \n");
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("Erro na Conexão");
        }
    }

    public void addDespesa(String addDesp){
        String sqlInsert;
        sqlInsert = "insert into tipo_de_despesa(descricao) values ('"+addDesp+"')";
        mysql.execute(sqlInsert);
    }

}

You also need to start the connection before calling the method addDespesa, otherwise a nullPointerException.

I recommend reading of this post on the use of Try-with-Resources for database connection processing.

Browser other questions tagged

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