Finding variable from another method of the same Class

1

I have a class BancoDeDados and it contains two methods: conexao and addDespesa . The conexao method connects to my local database. The addDespesa method adds values to one of my tables, but it can not "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);
    }

}
    
asked by anonymous 16.09.2017 / 21:09

1 answer

2

Can not because of the variable scope . You created the variable as being local within the conexão() method, it will only exist there inside. If you want the variable to be accessible in every class, you need to increase the scope of the variable, such as 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 addDespesa method, otherwise a nullPointerException will occur.

I recommend reading this post about using try- with-resources for database connection treatments.

    
16.09.2017 / 21:16