I can not use the connection to the database outside the constructor, why?

advertisements

Why can't I execute a query outside the constructor? I can't use the variables I declared in the constructor. Why not? Do I have to put the database connection in a method with parameters?

public class main extends javax.swing.JFrame
{
    DefaultListModel model = new DefaultListModel();

    public main()
    {
        initComponents();
        try
        {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "password");
            Statement stat = con.createStatement();
            ResultSet resultaat = stat.executeQuery(query);

            while (resultaat.next())
            {
                model.addElement(resultaat.getString(2));
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex);
        }
    }
}


con is withing your constructor scope . Use

Connection con;

as class variable and in constructor

con = DriverManager.getConnection("jdbc:mysql://localhost/project","root","password");

use this only. Do same for required variables. Which you need to use through out the class.